mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-11-29 00:39:27 +03:00
feat(core): improve sync stability (#15883)
#### PR Dependency Tree * **PR #15883** 👈 This tree was auto-generated by [Charcoal](https://github.com/danerwilliams/charcoal) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Document creation can now recover incomplete registrations without recreating document content. * Document updates can detect revision conflicts, helping prevent changes from overwriting newer edits. * **Improvements** * Document sync and update handling are improved across desktop, Android, and iOS. * Workspace metadata and legacy document pages are handled more consistently during migration and recovery. * Creator and editor details are better preserved when documents are recovered or compacted. * **Configuration** * Removed the experimental document-merge setting. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
1 parent
a2dbbec72b
commit
3d25727076
95 files changed
+6175
-804
No files matched your search
@@ -763,11 +763,6 @@
|
||||
"type": "object",
|
||||
"description": "Configuration for doc module",
|
||||
"properties": {
|
||||
"experimental.yocto": {
|
||||
"type": "boolean",
|
||||
"description": "Use `y-octo` to merge updates at the same time when merging using Yjs.\n@default false",
|
||||
"default": false
|
||||
},
|
||||
"history.interval": {
|
||||
"type": "number",
|
||||
"description": "The minimum time interval in milliseconds of creating a new history snapshot when doc get updated.\n@default 600000",
|
||||
|
||||
Generated
+9
-8
@@ -93,9 +93,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "affine_doc_loader"
|
||||
version = "0.3.0"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b76c6e41afed3a846efaa361409da555d08b4caf1338205746dadde2604bee2b"
|
||||
checksum = "b0c5ec95b331a6d642c71c1f304435a588728363d6abd76fa42cebf6ddd37a17"
|
||||
dependencies = [
|
||||
"affine_merge",
|
||||
"chrono",
|
||||
@@ -110,9 +110,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "affine_importer"
|
||||
version = "0.3.0"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "90082593d61bd6fd8b550ca1e2de65654ac2b15da7d4396c6c1471e86d191d9d"
|
||||
checksum = "8fa22a0e948ed16399ae98ca26c285bda6e6894cd463c4b9dd40dc8b37092b74"
|
||||
dependencies = [
|
||||
"affine_doc_loader",
|
||||
"bytes",
|
||||
@@ -161,9 +161,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "affine_merge"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "512fbcc04148bdb3d5193159d73a6f9b5e685b4a5a9fbc421d87abfa79d89b29"
|
||||
checksum = "d7ca4a08c70cabba37e19379db35f429394c0600a16b22e2f6f25754676b1e19"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.18",
|
||||
@@ -11373,9 +11373,9 @@ checksum = "aee1b19627c7c60102ab80d3a9cbe18de90bfe03bfa6c3715447681f0e8c8af6"
|
||||
|
||||
[[package]]
|
||||
name = "y-octo"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce9830799db2d14bbd6b36f9e9bc6047ba01cdb6f5f30731113314dc39b7cc67"
|
||||
checksum = "e381655b2334e81e3088ff85d021c31a2ec950dac0ae96b538aea674321e7d3c"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"arbitrary",
|
||||
@@ -11388,6 +11388,7 @@ dependencies = [
|
||||
"nom 8.0.0",
|
||||
"ordered-float",
|
||||
"rand 0.10.1",
|
||||
"ryu-js",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"smol_str",
|
||||
|
||||
+3
-3
@@ -16,8 +16,8 @@ resolver = "3"
|
||||
[workspace.dependencies]
|
||||
aes-gcm = "0.10"
|
||||
affine_common = { path = "./packages/common/native" }
|
||||
affine_doc_loader = "0.3.0"
|
||||
affine_importer = "0.3.0"
|
||||
affine_doc_loader = "0.4.0"
|
||||
affine_importer = "0.4.0"
|
||||
affine_nbstore = { path = "./packages/frontend/native/nbstore" }
|
||||
affine_preview = { version = "0.1.0", default-features = false }
|
||||
anyhow = "1"
|
||||
@@ -111,7 +111,7 @@ resolver = "3"
|
||||
"Win32_UI_Shell_PropertiesSystem",
|
||||
] }
|
||||
windows-core = { version = "0.62" }
|
||||
y-octo = { version = "0.2.0", features = ["large_refs"] }
|
||||
y-octo = { version = "0.3.0", features = ["large_refs"] }
|
||||
zeroize = "1.9"
|
||||
zip = "9.0.5"
|
||||
|
||||
|
||||
Vendored
+31
-1
@@ -49,7 +49,8 @@ export declare class BackendRuntime {
|
||||
*/
|
||||
compactPendingDocUpdates(workspaceId: string, docId: string, batchLimit: number, historyMinIntervalMs: number, historyMaxAgeSeconds: number): Promise<RuntimeDocCompactionResult>
|
||||
getCurrentWorkspaceDocV1(workspaceId: string, docId: string): Promise<RuntimeDocRecord | null>
|
||||
upsertDocSnapshot(workspaceId: string, docId: string, blob: Buffer, timestampMs: number, editorId?: string | undefined | null): Promise<boolean>
|
||||
getWorkspaceDocCreatorV1(workspaceId: string, docId: string): Promise<string | null>
|
||||
upsertDocSnapshot(workspaceId: string, docId: string, blob: Buffer, timestampMs: number, editorId?: string | undefined | null, creatorId?: string | undefined | null, fromInitialUpdates?: boolean | undefined | null): Promise<boolean>
|
||||
createDocHistory(input: RuntimeDocHistoryInput): Promise<boolean>
|
||||
appendWorkspaceDocUpdatesV1(input: AppendWorkspaceDocUpdatesInputV1): Promise<WorkspaceDocWriteResultV1>
|
||||
appendWorkspaceDocUpdatesTrustedV1(input: AppendWorkspaceDocUpdatesTrustedInputV1): Promise<number>
|
||||
@@ -243,6 +244,7 @@ export interface AppendWorkspaceDocUpdatesInputV1 {
|
||||
writeIntent: WorkspaceDocWriteIntentV1
|
||||
expectedPermissionGeneration?: number
|
||||
protocolVersion?: number
|
||||
expectedCurrentTimestamp?: number
|
||||
}
|
||||
|
||||
export interface AppendWorkspaceDocUpdatesTrustedInputV1 {
|
||||
@@ -250,6 +252,7 @@ export interface AppendWorkspaceDocUpdatesTrustedInputV1 {
|
||||
docId: string
|
||||
updates: Array<Buffer>
|
||||
editorId?: string
|
||||
expectedCurrentTimestamp?: number
|
||||
}
|
||||
|
||||
export declare function assertSafeUrl(request: AssertSafeUrlRequest): void
|
||||
@@ -612,6 +615,8 @@ export interface CreateByokProfileInput {
|
||||
*/
|
||||
export declare function createDocWithMarkdown(title: string, markdown: string, docId: string, context?: DocWriteContext | undefined | null): Buffer
|
||||
|
||||
export declare function diffDocUpdateV1(update: Buffer, stateVector: Buffer): Buffer
|
||||
|
||||
export interface DocumentEmbeddingProjectionInput {
|
||||
docId: string
|
||||
revision: string
|
||||
@@ -643,6 +648,8 @@ export interface EmbeddingHealth {
|
||||
workerRunning: boolean
|
||||
}
|
||||
|
||||
export declare function encodeStateVectorFromUpdateV1(update: Buffer): Buffer
|
||||
|
||||
export interface EnsureWorkspaceBlobArtifactInput {
|
||||
workspaceId: string
|
||||
blobId: string
|
||||
@@ -656,6 +663,12 @@ export declare function evaluateLocalRedirect(input: string, baseUrl: string, al
|
||||
|
||||
export declare function evaluateRedirectUri(input: string, baseUrl: string, allowedOrigins: Array<string>, trustedDomains: Array<string>, queryPairs: Array<UrlQueryPair>): string
|
||||
|
||||
export declare function extractDocRecoveryFacts(docBin: Buffer, propertiesBin: Buffer | undefined | null, targetDocId: string): NativeDocRecoveryFacts
|
||||
|
||||
export declare function extractRootDocIdAliases(rootDocBin: Buffer): Record<string, string>
|
||||
|
||||
export declare function extractWorkspaceLifecycleRootPages(rootDocBin: Buffer, maxStructs?: number | undefined | null): Array<NativeLifecycleRootPage>
|
||||
|
||||
export declare function fetchRemoteAttachment(request: RemoteAttachmentFetchRequest): Promise<RemoteAttachmentFetchResponse>
|
||||
|
||||
export declare function fromModelName(modelName: string): Tokenizer | null
|
||||
@@ -849,6 +862,8 @@ export interface MatchEmbeddingCandidatesInput {
|
||||
|
||||
export declare function mergeUpdates(updates: Array<Buffer>): Buffer
|
||||
|
||||
export declare function migrateRootDocPages(rootDocBin: Buffer): Buffer | null
|
||||
|
||||
export declare function mintChallengeResponse(resource: string, bits?: number | undefined | null): Promise<string>
|
||||
|
||||
export interface ModelConditionsContract {
|
||||
@@ -943,6 +958,12 @@ export interface NativeDocBounds {
|
||||
height: number
|
||||
}
|
||||
|
||||
export interface NativeDocRecoveryFacts {
|
||||
title: string
|
||||
existingCreatedBy?: string
|
||||
existingUpdatedBy?: string
|
||||
}
|
||||
|
||||
export interface NativeDocumentSearchProjection {
|
||||
version: number
|
||||
docId: string
|
||||
@@ -970,6 +991,11 @@ export interface NativeDocumentSearchUnit {
|
||||
text: string
|
||||
}
|
||||
|
||||
export interface NativeLifecycleRootPage {
|
||||
docId: string
|
||||
trashed: boolean
|
||||
}
|
||||
|
||||
export interface NativeMarkdownResult {
|
||||
title: string
|
||||
markdown: string
|
||||
@@ -1219,6 +1245,8 @@ export interface ResolveEntitlementInput {
|
||||
|
||||
export declare function resolveEntitlementV1(input: ResolveEntitlementInput): ResolvedEntitlement
|
||||
|
||||
export declare function revertDocUpdateV1(currentSnapshot: Buffer, targetSnapshot: Buffer): Buffer
|
||||
|
||||
export interface RotateByokCredentialInput {
|
||||
workspaceId: string
|
||||
profileId: string
|
||||
@@ -1871,6 +1899,8 @@ export declare function updateDocTitle(existingBinary: Buffer, title: string, do
|
||||
*/
|
||||
export declare function updateDocWithMarkdown(existingBinary: Buffer, newMarkdown: string, docId: string, context?: DocWriteContext | undefined | null): Buffer
|
||||
|
||||
export declare function updateExistingRootDocMetaTitle(rootDocBin: Buffer, docId: string, title: string): Buffer | null
|
||||
|
||||
/**
|
||||
* Updates a document title in the workspace root doc's meta.pages array.
|
||||
*
|
||||
|
||||
@@ -15,8 +15,9 @@ use napi::bindgen_prelude::*;
|
||||
use napi_derive::napi;
|
||||
use tokio::sync::{OwnedSemaphorePermit, Semaphore, TryAcquireError};
|
||||
pub use write::{
|
||||
DocWriteContext, add_doc_to_root_doc, build_public_root_doc, create_doc_with_markdown, update_doc_properties,
|
||||
update_doc_title, update_doc_with_markdown, update_root_doc_meta_title,
|
||||
DocWriteContext, add_doc_to_root_doc, build_public_root_doc, create_doc_with_markdown, migrate_root_doc_pages,
|
||||
update_doc_properties, update_doc_title, update_doc_with_markdown, update_existing_root_doc_meta_title,
|
||||
update_root_doc_meta_title,
|
||||
};
|
||||
|
||||
pub(crate) fn try_validation_slot() -> std::result::Result<OwnedSemaphorePermit, TryAcquireError> {
|
||||
@@ -377,3 +378,566 @@ pub fn read_all_doc_ids_from_root_doc(doc_bin: Buffer, include_trash: Option<boo
|
||||
)?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[napi(object)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct NativeLifecycleRootPage {
|
||||
pub doc_id: String,
|
||||
pub trashed: bool,
|
||||
}
|
||||
|
||||
#[napi(object)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct NativeDocRecoveryFacts {
|
||||
pub title: String,
|
||||
pub existing_created_by: Option<String>,
|
||||
pub existing_updated_by: Option<String>,
|
||||
}
|
||||
|
||||
fn is_empty_doc_bin(bin: &[u8]) -> bool {
|
||||
bin.is_empty() || bin == [0, 0]
|
||||
}
|
||||
|
||||
fn non_empty_string(value: &str) -> Option<String> {
|
||||
if value.trim().is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(value.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_existing_properties(properties_bin: &[u8], target_doc_id: &str) -> Result<(Option<String>, Option<String>)> {
|
||||
if is_empty_doc_bin(properties_bin) {
|
||||
return Ok((None, None));
|
||||
}
|
||||
match y_octo::ReadDoc::from_full_update_v1(properties_bin.to_vec()) {
|
||||
Ok(doc) => {
|
||||
let Some(entry) = doc.map(target_doc_id) else {
|
||||
return Ok((None, None));
|
||||
};
|
||||
let created_by = entry
|
||||
.get("createdBy")
|
||||
.and_then(|v| v.as_any())
|
||||
.and_then(|a| a.as_str())
|
||||
.and_then(non_empty_string);
|
||||
let updated_by = entry
|
||||
.get("updatedBy")
|
||||
.and_then(|v| v.as_any())
|
||||
.and_then(|a| a.as_str())
|
||||
.and_then(non_empty_string);
|
||||
Ok((created_by, updated_by))
|
||||
}
|
||||
Err(y_octo::ReadError::IncompleteSnapshot(_)) => {
|
||||
let doc = map_napi_err(y_octo::Doc::try_from_binary_v1(properties_bin), Status::GenericFailure)?;
|
||||
let Ok(entry) = doc.get_map(target_doc_id) else {
|
||||
return Ok((None, None));
|
||||
};
|
||||
let created_by = match entry.get("createdBy") {
|
||||
Some(y_octo::Value::Any(y_octo::Any::String(s))) => non_empty_string(&s),
|
||||
_ => None,
|
||||
};
|
||||
let updated_by = match entry.get("updatedBy") {
|
||||
Some(y_octo::Value::Any(y_octo::Any::String(s))) => non_empty_string(&s),
|
||||
_ => None,
|
||||
};
|
||||
Ok((created_by, updated_by))
|
||||
}
|
||||
Err(err @ y_octo::ReadError::ResourceLimit(_)) => Err(napi::Error::new(
|
||||
Status::GenericFailure,
|
||||
format!("[affine-doc:resource_limit] {err}"),
|
||||
)),
|
||||
Err(err) => Err(napi::Error::new(Status::GenericFailure, err.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn extract_doc_recovery_facts(
|
||||
doc_bin: Buffer,
|
||||
properties_bin: Option<Buffer>,
|
||||
target_doc_id: String,
|
||||
) -> Result<NativeDocRecoveryFacts> {
|
||||
let doc_bytes = doc_bin.to_vec();
|
||||
let title = if is_empty_doc_bin(&doc_bytes) {
|
||||
String::new()
|
||||
} else {
|
||||
map_napi_err(doc_loader::parse_page_doc(doc_bytes, Some(0)), Status::GenericFailure)?
|
||||
.map(|page| page.title)
|
||||
.unwrap_or_default()
|
||||
};
|
||||
|
||||
let (existing_created_by, existing_updated_by) = match properties_bin {
|
||||
Some(buf) => extract_existing_properties(&buf, &target_doc_id)?,
|
||||
None => (None, None),
|
||||
};
|
||||
|
||||
Ok(NativeDocRecoveryFacts {
|
||||
title,
|
||||
existing_created_by,
|
||||
existing_updated_by,
|
||||
})
|
||||
}
|
||||
|
||||
fn extract_aliases_from_read_doc(doc: &y_octo::ReadDoc) -> HashMap<String, String> {
|
||||
let mut aliases = HashMap::new();
|
||||
let Some(meta) = doc.map("meta") else {
|
||||
return aliases;
|
||||
};
|
||||
let Some(y_octo::ReadValue::Array(pages)) = meta.get("pages") else {
|
||||
return aliases;
|
||||
};
|
||||
let Some(spaces) = doc.map("spaces") else {
|
||||
return aliases;
|
||||
};
|
||||
for entry in pages.iter() {
|
||||
let y_octo::ReadValue::Map(page) = entry else {
|
||||
continue;
|
||||
};
|
||||
let Some(id) = page.get("id").and_then(|v| v.as_any()).and_then(|a| a.as_str()) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(y_octo::ReadValue::Doc { guid, .. }) = spaces.get(id) {
|
||||
aliases.insert(id.to_string(), guid.to_string());
|
||||
}
|
||||
}
|
||||
aliases
|
||||
}
|
||||
|
||||
fn extract_aliases_from_doc(doc: &y_octo::Doc) -> HashMap<String, String> {
|
||||
let mut aliases = HashMap::new();
|
||||
let Ok(meta) = doc.get_map("meta") else {
|
||||
return aliases;
|
||||
};
|
||||
let Some(y_octo::Value::Array(pages)) = meta.get("pages") else {
|
||||
return aliases;
|
||||
};
|
||||
let Ok(spaces) = doc.get_map("spaces") else {
|
||||
return aliases;
|
||||
};
|
||||
for entry in pages.iter() {
|
||||
let y_octo::Value::Map(page) = entry else {
|
||||
continue;
|
||||
};
|
||||
let Some(y_octo::Value::Any(y_octo::Any::String(id))) = page.get("id") else {
|
||||
continue;
|
||||
};
|
||||
if let Some(y_octo::Value::Doc(subdoc)) = spaces.get(&id) {
|
||||
aliases.insert(id, subdoc.guid().to_string());
|
||||
}
|
||||
}
|
||||
aliases
|
||||
}
|
||||
|
||||
pub(crate) const WORKSPACE_LIFECYCLE_MIGRATION_READ_LIMITS: y_octo::ReadLimits = y_octo::ReadLimits {
|
||||
max_input_bytes: 256 * 1024 * 1024,
|
||||
max_structs: 16_000_000,
|
||||
max_clients: 200_000,
|
||||
max_collection_entries: 32_000_000,
|
||||
max_any_depth: y_octo::Any::DEFAULT_MAX_DEPTH,
|
||||
max_content_bytes: 256 * 1024 * 1024,
|
||||
};
|
||||
|
||||
fn extract_root_doc_id_aliases_with_limits(
|
||||
bytes: Vec<u8>,
|
||||
limits: y_octo::ReadLimits,
|
||||
) -> Result<HashMap<String, String>> {
|
||||
if is_empty_doc_bin(&bytes) {
|
||||
return Ok(HashMap::new());
|
||||
}
|
||||
|
||||
match y_octo::ReadDoc::from_full_update_v1_with_limits(bytes.clone(), limits) {
|
||||
Ok(doc) => Ok(extract_aliases_from_read_doc(&doc)),
|
||||
Err(y_octo::ReadError::IncompleteSnapshot(_)) => {
|
||||
let doc = map_napi_err(y_octo::Doc::try_from_binary_v1(&bytes), Status::GenericFailure)?;
|
||||
Ok(extract_aliases_from_doc(&doc))
|
||||
}
|
||||
Err(err @ y_octo::ReadError::ResourceLimit(_)) => Err(napi::Error::new(
|
||||
Status::GenericFailure,
|
||||
format!("[affine-doc:resource_limit] {err}"),
|
||||
)),
|
||||
Err(err) => Err(napi::Error::new(Status::GenericFailure, err.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn extract_root_doc_id_aliases(root_doc_bin: Buffer) -> Result<HashMap<String, String>> {
|
||||
extract_root_doc_id_aliases_with_limits(root_doc_bin.to_vec(), y_octo::ReadLimits::default())
|
||||
}
|
||||
|
||||
fn push_lifecycle_page(pages_out: &mut Vec<NativeLifecycleRootPage>, doc_id: &str, trashed: bool) {
|
||||
if !doc_id.trim().is_empty() {
|
||||
pages_out.push(NativeLifecycleRootPage {
|
||||
doc_id: doc_id.to_string(),
|
||||
trashed,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn push_lifecycle_page_from_read_any(pages_out: &mut Vec<NativeLifecycleRootPage>, any: &y_octo::ReadAny<'_>) {
|
||||
if let Some(doc_id) = any.get("id").and_then(|a| a.as_str()) {
|
||||
let trashed = any.get("trash").and_then(|a| a.as_bool()) == Some(true);
|
||||
push_lifecycle_page(pages_out, doc_id, trashed);
|
||||
}
|
||||
}
|
||||
|
||||
fn push_lifecycle_page_from_object(
|
||||
pages_out: &mut Vec<NativeLifecycleRootPage>,
|
||||
object: &y_octo::AHashMap<String, y_octo::Any>,
|
||||
) {
|
||||
if let Some(y_octo::Any::String(doc_id)) = object.get("id") {
|
||||
let trashed = matches!(object.get("trash"), Some(y_octo::Any::True));
|
||||
push_lifecycle_page(pages_out, doc_id, trashed);
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_lifecycle_pages_from_read_doc(doc: &y_octo::ReadDoc) -> Vec<NativeLifecycleRootPage> {
|
||||
let mut pages_out = Vec::new();
|
||||
let Some(meta) = doc.map("meta") else {
|
||||
return pages_out;
|
||||
};
|
||||
match meta.get("pages") {
|
||||
Some(y_octo::ReadValue::Array(pages)) => {
|
||||
for entry in pages.iter() {
|
||||
match entry {
|
||||
y_octo::ReadValue::Map(page) => {
|
||||
if let Some(doc_id) = page.get("id").and_then(|v| v.as_any()).and_then(|a| a.as_str()) {
|
||||
let trashed = page.get("trash").and_then(|v| v.as_any()).and_then(|a| a.as_bool()) == Some(true);
|
||||
push_lifecycle_page(&mut pages_out, doc_id, trashed);
|
||||
}
|
||||
}
|
||||
y_octo::ReadValue::Any(any) => push_lifecycle_page_from_read_any(&mut pages_out, &any),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(y_octo::ReadValue::Any(any)) => {
|
||||
if let Some(entries) = any.array() {
|
||||
for entry in entries {
|
||||
push_lifecycle_page_from_read_any(&mut pages_out, &entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
pages_out
|
||||
}
|
||||
|
||||
fn extract_lifecycle_pages_from_doc(doc: &y_octo::Doc) -> Vec<NativeLifecycleRootPage> {
|
||||
let mut pages_out = Vec::new();
|
||||
let Ok(meta) = doc.get_map("meta") else {
|
||||
return pages_out;
|
||||
};
|
||||
match meta.get("pages") {
|
||||
Some(y_octo::Value::Array(pages)) => {
|
||||
for entry in pages.iter() {
|
||||
match entry {
|
||||
y_octo::Value::Map(page) => {
|
||||
if let Some(y_octo::Value::Any(y_octo::Any::String(doc_id))) = page.get("id") {
|
||||
let trashed = matches!(page.get("trash"), Some(y_octo::Value::Any(y_octo::Any::True)));
|
||||
push_lifecycle_page(&mut pages_out, &doc_id, trashed);
|
||||
}
|
||||
}
|
||||
y_octo::Value::Any(y_octo::Any::Object(object)) => push_lifecycle_page_from_object(&mut pages_out, &object),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(y_octo::Value::Any(y_octo::Any::Array(entries))) => {
|
||||
for entry in entries {
|
||||
if let y_octo::Any::Object(object) = entry {
|
||||
push_lifecycle_page_from_object(&mut pages_out, &object);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
pages_out
|
||||
}
|
||||
|
||||
fn extract_workspace_lifecycle_root_pages_with_limits(
|
||||
bytes: Vec<u8>,
|
||||
limits: y_octo::ReadLimits,
|
||||
) -> Result<Vec<NativeLifecycleRootPage>> {
|
||||
if is_empty_doc_bin(&bytes) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
match y_octo::ReadDoc::from_full_update_v1_with_limits(bytes.clone(), limits) {
|
||||
Ok(doc) => Ok(extract_lifecycle_pages_from_read_doc(&doc)),
|
||||
Err(y_octo::ReadError::IncompleteSnapshot(_)) => {
|
||||
let doc = map_napi_err(y_octo::Doc::try_from_binary_v1(&bytes), Status::GenericFailure)?;
|
||||
Ok(extract_lifecycle_pages_from_doc(&doc))
|
||||
}
|
||||
Err(err @ y_octo::ReadError::ResourceLimit(_)) => Err(napi::Error::new(
|
||||
Status::GenericFailure,
|
||||
format!("[affine-doc:resource_limit] {err}"),
|
||||
)),
|
||||
Err(err) => Err(napi::Error::new(Status::GenericFailure, err.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn extract_workspace_lifecycle_root_pages(
|
||||
root_doc_bin: Buffer,
|
||||
max_structs: Option<u32>,
|
||||
) -> Result<Vec<NativeLifecycleRootPage>> {
|
||||
let limits = match max_structs {
|
||||
Some(limit) => y_octo::ReadLimits {
|
||||
max_structs: limit as usize,
|
||||
..WORKSPACE_LIFECYCLE_MIGRATION_READ_LIMITS
|
||||
},
|
||||
None => WORKSPACE_LIFECYCLE_MIGRATION_READ_LIMITS,
|
||||
};
|
||||
extract_workspace_lifecycle_root_pages_with_limits(root_doc_bin.to_vec(), limits)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use y_octo::{AHashMap, Any, Doc, DocOptions, HashMapExt, Value};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn extract_root_doc_id_aliases_handles_empty_and_subdoc_guids() {
|
||||
assert!(extract_root_doc_id_aliases(Buffer::from(vec![])).unwrap().is_empty());
|
||||
assert!(
|
||||
extract_root_doc_id_aliases(Buffer::from(vec![0, 0]))
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
|
||||
let doc = Doc::default();
|
||||
let mut meta = doc.get_or_create_map("meta").unwrap();
|
||||
let mut pages = doc.create_array().unwrap();
|
||||
let mut page1 = doc.create_map().unwrap();
|
||||
page1.insert("id".into(), Any::String("logical-1".into())).unwrap();
|
||||
pages.push(Value::Map(page1)).unwrap();
|
||||
let mut page2 = doc.create_map().unwrap();
|
||||
page2.insert("id".into(), Any::String("logical-2".into())).unwrap();
|
||||
pages.push(Value::Map(page2)).unwrap();
|
||||
meta.insert("pages".into(), Value::Array(pages)).unwrap();
|
||||
|
||||
let mut spaces = doc.get_or_create_map("spaces").unwrap();
|
||||
let subdoc = DocOptions::new().with_guid("storage-guid-1".into()).build();
|
||||
spaces.insert("logical-1".into(), Value::Doc(subdoc)).unwrap();
|
||||
spaces
|
||||
.insert("logical-2".into(), Value::Any(Any::String("not-a-subdoc".into())))
|
||||
.unwrap();
|
||||
|
||||
let bin = doc.encode_update_v1().unwrap();
|
||||
let aliases = extract_root_doc_id_aliases(Buffer::from(bin)).unwrap();
|
||||
assert_eq!(aliases.len(), 1);
|
||||
assert_eq!(aliases.get("logical-1").map(String::as_str), Some("storage-guid-1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_workspace_lifecycle_root_pages_preserves_strict_trash_and_legacy_shapes() {
|
||||
assert!(
|
||||
extract_workspace_lifecycle_root_pages(Buffer::from(vec![]), None)
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
assert!(extract_workspace_lifecycle_root_pages(Buffer::from(vec![255]), None).is_err());
|
||||
|
||||
// Mixed Y.Array with Map + Any::Object, strict boolean trash check, and
|
||||
// whitespace id skip
|
||||
let doc = Doc::default();
|
||||
let mut meta = doc.get_or_create_map("meta").unwrap();
|
||||
let mut pages = doc.create_array().unwrap();
|
||||
|
||||
let mut p1 = doc.create_map().unwrap();
|
||||
p1.insert("id".into(), Any::String("doc-trashed".into())).unwrap();
|
||||
p1.insert("trash".into(), Any::True).unwrap();
|
||||
pages.push(Value::Map(p1)).unwrap();
|
||||
|
||||
let mut p2 = doc.create_map().unwrap();
|
||||
p2.insert("id".into(), Any::String("doc-string-trash".into())).unwrap();
|
||||
p2.insert("trash".into(), Any::String("true".into())).unwrap();
|
||||
pages.push(Value::Map(p2)).unwrap();
|
||||
|
||||
let mut p3 = doc.create_map().unwrap();
|
||||
p3.insert("id".into(), Any::String(" ".into())).unwrap();
|
||||
pages.push(Value::Map(p3)).unwrap();
|
||||
|
||||
let mut legacy_obj = AHashMap::new();
|
||||
legacy_obj.insert("id".into(), Any::String("doc-legacy-obj".into()));
|
||||
legacy_obj.insert("trash".into(), Any::True);
|
||||
pages.push(Value::Any(Any::Object(Box::new(legacy_obj)))).unwrap();
|
||||
|
||||
meta.insert("pages".into(), Value::Array(pages)).unwrap();
|
||||
let bin = doc.encode_update_v1().unwrap();
|
||||
|
||||
let result = extract_workspace_lifecycle_root_pages(Buffer::from(bin), None).unwrap();
|
||||
assert_eq!(
|
||||
result,
|
||||
vec![
|
||||
NativeLifecycleRootPage {
|
||||
doc_id: "doc-trashed".into(),
|
||||
trashed: true
|
||||
},
|
||||
NativeLifecycleRootPage {
|
||||
doc_id: "doc-string-trash".into(),
|
||||
trashed: false
|
||||
},
|
||||
NativeLifecycleRootPage {
|
||||
doc_id: "doc-legacy-obj".into(),
|
||||
trashed: true
|
||||
},
|
||||
]
|
||||
);
|
||||
|
||||
// Outer Any::Array shape (matching Yjs `meta.set('pages', [obj1, obj2])`)
|
||||
let doc2 = Doc::default();
|
||||
let mut meta2 = doc2.get_or_create_map("meta").unwrap();
|
||||
let mut obj1 = AHashMap::new();
|
||||
obj1.insert("id".into(), Any::String("doc-arr-1".into()));
|
||||
obj1.insert("trash".into(), Any::Integer(1));
|
||||
let mut obj2 = AHashMap::new();
|
||||
obj2.insert("id".into(), Any::String("doc-arr-2".into()));
|
||||
obj2.insert("trash".into(), Any::True);
|
||||
meta2
|
||||
.insert(
|
||||
"pages".into(),
|
||||
Any::Array(vec![Any::Object(Box::new(obj1)), Any::Object(Box::new(obj2))]),
|
||||
)
|
||||
.unwrap();
|
||||
let bin2 = doc2.encode_update_v1().unwrap();
|
||||
let result2 = extract_workspace_lifecycle_root_pages(Buffer::from(bin2), None).unwrap();
|
||||
assert_eq!(
|
||||
result2,
|
||||
vec![
|
||||
NativeLifecycleRootPage {
|
||||
doc_id: "doc-arr-1".into(),
|
||||
trashed: false,
|
||||
},
|
||||
NativeLifecycleRootPage {
|
||||
doc_id: "doc-arr-2".into(),
|
||||
trashed: true,
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_extractors_enforce_resource_limits_and_fallback_on_incomplete_snapshot() {
|
||||
let doc = Doc::default();
|
||||
let mut meta = doc.get_or_create_map("meta").unwrap();
|
||||
let mut pages = doc.create_array().unwrap();
|
||||
let mut page1 = doc.create_map().unwrap();
|
||||
page1.insert("id".into(), Any::String("logical-limit".into())).unwrap();
|
||||
page1.insert("trash".into(), Any::True).unwrap();
|
||||
pages.push(Value::Map(page1)).unwrap();
|
||||
meta.insert("pages".into(), Value::Array(pages)).unwrap();
|
||||
let mut spaces = doc.get_or_create_map("spaces").unwrap();
|
||||
let subdoc = DocOptions::new().with_guid("storage-limit".into()).build();
|
||||
spaces.insert("logical-limit".into(), Value::Doc(subdoc)).unwrap();
|
||||
let bin = doc.encode_update_v1().unwrap();
|
||||
|
||||
let tiny_limits = y_octo::ReadLimits {
|
||||
max_structs: 1,
|
||||
..y_octo::ReadLimits::default()
|
||||
};
|
||||
assert!(matches!(
|
||||
y_octo::ReadDoc::from_full_update_v1_with_limits(bin.clone(), tiny_limits.clone()),
|
||||
Err(y_octo::ReadError::ResourceLimit(_))
|
||||
));
|
||||
|
||||
// Online alias extraction must enforce resource limits with explicit prefix
|
||||
// without falling back to unbounded Doc.
|
||||
let alias_err = extract_root_doc_id_aliases_with_limits(bin.clone(), tiny_limits.clone()).unwrap_err();
|
||||
assert!(alias_err.reason.contains("[affine-doc:resource_limit]"));
|
||||
|
||||
// Lifecycle extraction must also enforce its explicit limit boundary...
|
||||
let lifecycle_err = extract_workspace_lifecycle_root_pages(Buffer::from(bin.clone()), Some(1)).unwrap_err();
|
||||
assert!(lifecycle_err.reason.contains("[affine-doc:resource_limit]"));
|
||||
// ...while succeeding within WORKSPACE_LIFECYCLE_MIGRATION_READ_LIMITS.
|
||||
let lifecycle_pages = extract_workspace_lifecycle_root_pages(Buffer::from(bin), None).unwrap();
|
||||
assert_eq!(
|
||||
lifecycle_pages,
|
||||
vec![NativeLifecycleRootPage {
|
||||
doc_id: "logical-limit".into(),
|
||||
trashed: true,
|
||||
}]
|
||||
);
|
||||
|
||||
// IncompleteSnapshot (multi-client update where one client has a Skip)
|
||||
// still falls back to Doc and reads the complete client's entries.
|
||||
let doc_c1 = DocOptions::new().with_client_id(1).build();
|
||||
let mut delta_meta = doc_c1.get_or_create_map("meta").unwrap();
|
||||
let mut delta_pages = doc_c1.create_array().unwrap();
|
||||
let mut delta_page = doc_c1.create_map().unwrap();
|
||||
delta_page
|
||||
.insert("id".into(), Any::String("delta-doc-1".into()))
|
||||
.unwrap();
|
||||
delta_page.insert("trash".into(), Any::True).unwrap();
|
||||
delta_pages.push(Value::Map(delta_page)).unwrap();
|
||||
delta_meta.insert("pages".into(), Value::Array(delta_pages)).unwrap();
|
||||
let mut delta_spaces = doc_c1.get_or_create_map("spaces").unwrap();
|
||||
let delta_subdoc = DocOptions::new().with_guid("delta-guid-1".into()).build();
|
||||
delta_spaces
|
||||
.insert("delta-doc-1".into(), Value::Doc(delta_subdoc))
|
||||
.unwrap();
|
||||
|
||||
let mut doc_c2 = DocOptions::new().with_client_id(2).build();
|
||||
let mut c2_other = doc_c2.get_or_create_map("other").unwrap();
|
||||
c2_other.insert("a".into(), Any::String("first".into())).unwrap();
|
||||
let sv_c2 = doc_c2.get_state_vector();
|
||||
c2_other.insert("b".into(), Any::String("second".into())).unwrap();
|
||||
doc_c2
|
||||
.apply_update_from_binary_v1(doc_c1.encode_update_v1().unwrap())
|
||||
.unwrap();
|
||||
|
||||
let delta_bin = doc_c2.encode_state_as_update_v1(&sv_c2).unwrap();
|
||||
assert!(matches!(
|
||||
y_octo::ReadDoc::from_full_update_v1_with_limits(delta_bin.clone(), y_octo::ReadLimits::default()),
|
||||
Err(y_octo::ReadError::IncompleteSnapshot(_))
|
||||
));
|
||||
|
||||
let delta_aliases = extract_root_doc_id_aliases(Buffer::from(delta_bin.clone())).unwrap();
|
||||
assert_eq!(
|
||||
delta_aliases.get("delta-doc-1").map(String::as_str),
|
||||
Some("delta-guid-1")
|
||||
);
|
||||
let delta_lifecycle = extract_workspace_lifecycle_root_pages(Buffer::from(delta_bin), None).unwrap();
|
||||
assert_eq!(
|
||||
delta_lifecycle,
|
||||
vec![NativeLifecycleRootPage {
|
||||
doc_id: "delta-doc-1".into(),
|
||||
trashed: true,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_doc_recovery_facts_reads_title_earliest_creator_and_properties() {
|
||||
let doc_bin = create_doc_with_markdown(
|
||||
"Persisted Title".into(),
|
||||
"Hello body".into(),
|
||||
"doc-facts-1".into(),
|
||||
Some(DocWriteContext {
|
||||
actor_user_id: "author-1".into(),
|
||||
timestamp_ms: 1000,
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let props_bin = update_doc_properties(
|
||||
Buffer::from(vec![]),
|
||||
"db$ws$docProperties".into(),
|
||||
"doc-facts-1".into(),
|
||||
Some("author-1".into()),
|
||||
Some("editor-2".into()),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let facts =
|
||||
extract_doc_recovery_facts(Buffer::from(doc_bin.to_vec()), Some(props_bin), "doc-facts-1".into()).unwrap();
|
||||
assert_eq!(facts.title, "Persisted Title");
|
||||
assert_eq!(facts.existing_created_by.as_deref(), Some("author-1"));
|
||||
assert_eq!(facts.existing_updated_by.as_deref(), Some("editor-2"));
|
||||
|
||||
let without_props = extract_doc_recovery_facts(doc_bin, None, "doc-facts-1".into()).unwrap();
|
||||
assert_eq!(without_props.title, "Persisted Title");
|
||||
assert_eq!(without_props.existing_created_by, None);
|
||||
assert_eq!(without_props.existing_updated_by, None);
|
||||
}
|
||||
}
|
||||
@@ -174,3 +174,25 @@ pub fn update_root_doc_meta_title(root_doc_bin: Buffer, doc_id: String, title: S
|
||||
)?;
|
||||
Ok(Buffer::from(result))
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn update_existing_root_doc_meta_title(
|
||||
root_doc_bin: Buffer,
|
||||
doc_id: String,
|
||||
title: String,
|
||||
) -> Result<Option<Buffer>> {
|
||||
let result = map_napi_err(
|
||||
doc_loader::update_existing_root_doc_meta_title(&root_doc_bin, &doc_id, &title),
|
||||
Status::GenericFailure,
|
||||
)?;
|
||||
Ok(result.map(Buffer::from))
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn migrate_root_doc_pages(root_doc_bin: Buffer) -> Result<Option<Buffer>> {
|
||||
let result = map_napi_err(
|
||||
doc_loader::migrate_root_doc_pages(&root_doc_bin),
|
||||
Status::GenericFailure,
|
||||
)?;
|
||||
Ok(result.map(Buffer::from))
|
||||
}
|
||||
@@ -24,7 +24,6 @@ mod utils;
|
||||
|
||||
use affine_common::napi_utils::map_napi_err;
|
||||
use napi::{Result, Status, bindgen_prelude::*};
|
||||
use y_octo::Update;
|
||||
|
||||
#[cfg(not(target_arch = "arm"))]
|
||||
#[global_allocator]
|
||||
@@ -39,13 +38,40 @@ pub fn merge_updates(updates: Vec<Buffer>) -> Result<Buffer> {
|
||||
Ok(map_napi_err(merged.encode_v1(), Status::GenericFailure)?.into())
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub fn diff_doc_update_v1(update: Buffer, state_vector: Buffer) -> Result<Buffer> {
|
||||
Ok(map_napi_err(y_octo::diff_update_v1(&update, &state_vector), Status::GenericFailure)?.into())
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub fn encode_state_vector_from_update_v1(update: Buffer) -> Result<Buffer> {
|
||||
Ok(
|
||||
map_napi_err(
|
||||
y_octo::encode_state_vector_from_update_v1(&update),
|
||||
Status::GenericFailure,
|
||||
)?
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub fn revert_doc_update_v1(current_snapshot: Buffer, target_snapshot: Buffer) -> Result<Buffer> {
|
||||
Ok(
|
||||
map_napi_err(
|
||||
y_octo::revert_update_v1(¤t_snapshot, &target_snapshot),
|
||||
Status::GenericFailure,
|
||||
)?
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Check whether a Yjs update binary can be decoded without applying it to a
|
||||
/// document state.
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn validate_doc_update(update: Buffer) -> Result<bool> {
|
||||
let permit = doc::try_validation_slot().map_err(|_| napi::Error::from_reason("doc_validation_unavailable"))?;
|
||||
let update = update.to_vec();
|
||||
blocking::spawn(permit, move || Update::decode_v1(update).is_ok())
|
||||
blocking::spawn(permit, move || y_octo::validate_update_v1(&update).is_ok())
|
||||
.await
|
||||
.map_err(|_| napi::Error::from_reason("doc_validation_unavailable"))
|
||||
}
|
||||
@@ -90,9 +116,95 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn y_octo_update_decode_accepts_valid_update_and_rejects_invalid_update() {
|
||||
assert!(Update::decode_v1(vec![0, 0]).is_ok());
|
||||
assert!(Update::decode_v1(vec![0]).is_err());
|
||||
fn y_octo_validate_update_v1_accepts_valid_and_rejects_invalid() {
|
||||
assert!(y_octo::validate_update_v1(&[0, 0]).is_ok());
|
||||
assert!(y_octo::validate_update_v1(&[0]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diff_and_state_vector_v1_roundtrip() {
|
||||
let doc = y_octo::DocOptions::new().with_client_id(1).build();
|
||||
let mut text = doc.get_or_create_text("content").unwrap();
|
||||
text.insert(0, "hello").unwrap();
|
||||
let update1 = doc.encode_update_v1().unwrap();
|
||||
let sv1 = encode_state_vector_from_update_v1(Buffer::from(update1)).unwrap();
|
||||
|
||||
text.insert(5, " world").unwrap();
|
||||
let update2 = doc.encode_update_v1().unwrap();
|
||||
let diff = diff_doc_update_v1(Buffer::from(update2), sv1).unwrap();
|
||||
assert!(y_octo::validate_update_v1(&diff).is_ok());
|
||||
assert_ne!(diff.as_ref(), &[0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revert_doc_update_v1_roundtrip_and_errors() {
|
||||
let doc = y_octo::DocOptions::new().with_client_id(1).build();
|
||||
let mut text = doc.get_or_create_text("content").unwrap();
|
||||
text.insert(0, "hello").unwrap();
|
||||
let target_snapshot = doc.encode_update_v1().unwrap();
|
||||
|
||||
text.insert(5, " world").unwrap();
|
||||
let current_snapshot = doc.encode_update_v1().unwrap();
|
||||
|
||||
let revert = revert_doc_update_v1(
|
||||
Buffer::from(current_snapshot.clone()),
|
||||
Buffer::from(target_snapshot.clone()),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let mut applied = y_octo::DocOptions::new().with_client_id(2).build();
|
||||
applied.apply_update_from_binary_v1(¤t_snapshot).unwrap();
|
||||
applied.apply_update_from_binary_v1(revert.as_ref()).unwrap();
|
||||
let applied_text = applied.get_or_create_text("content").unwrap();
|
||||
assert_eq!(applied_text.to_string(), "hello");
|
||||
|
||||
let err_corrupt = match revert_doc_update_v1(Buffer::from(vec![0]), Buffer::from(target_snapshot)) {
|
||||
Ok(_) => panic!("expected error for corrupt snapshot"),
|
||||
Err(err) => err,
|
||||
};
|
||||
assert_eq!(err_corrupt.status, Status::GenericFailure);
|
||||
|
||||
let unrelated = y_octo::DocOptions::new().with_client_id(9).build();
|
||||
let mut unrelated_text = unrelated.get_or_create_text("content").unwrap();
|
||||
unrelated_text.insert(0, "divergent").unwrap();
|
||||
let unrelated_snapshot = unrelated.encode_update_v1().unwrap();
|
||||
let err_non_ancestor = match revert_doc_update_v1(Buffer::from(current_snapshot), Buffer::from(unrelated_snapshot))
|
||||
{
|
||||
Ok(_) => panic!("expected error for non-ancestor snapshot"),
|
||||
Err(err) => err,
|
||||
};
|
||||
assert_eq!(err_non_ancestor.status, Status::GenericFailure);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streaming_validate_32mib_update_under_budget() {
|
||||
let doc = y_octo::DocOptions::new().with_client_id(7).build();
|
||||
let mut text = doc.get_or_create_text("payload").unwrap();
|
||||
let chunk = "a".repeat(32 * 1024 * 1024 - 128);
|
||||
text.insert(0, &chunk).unwrap();
|
||||
let valid_update = doc.encode_update_v1().unwrap();
|
||||
assert!(valid_update.len() >= 31 * 1024 * 1024);
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
assert!(y_octo::validate_update_v1(&valid_update).is_ok());
|
||||
let valid_elapsed = start.elapsed();
|
||||
|
||||
let mut invalid_update = valid_update;
|
||||
invalid_update.truncate(invalid_update.len() - 1);
|
||||
let start_invalid = std::time::Instant::now();
|
||||
assert!(y_octo::validate_update_v1(&invalid_update).is_err());
|
||||
let invalid_elapsed = start_invalid.elapsed();
|
||||
|
||||
eprintln!(
|
||||
"32 MiB validate_update_v1: valid={:.2}ms, invalid={:.2}ms",
|
||||
valid_elapsed.as_secs_f64() * 1000.0,
|
||||
invalid_elapsed.as_secs_f64() * 1000.0
|
||||
);
|
||||
#[cfg(not(debug_assertions))]
|
||||
{
|
||||
assert!(valid_elapsed < std::time::Duration::from_secs(1));
|
||||
assert!(invalid_elapsed < std::time::Duration::from_secs(1));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -22,6 +22,7 @@ struct Fixture {
|
||||
async fn setup() -> Option<Fixture> {
|
||||
let database_url = std::env::var("DATABASE_URL").ok()?;
|
||||
let pool = PgPool::connect(&database_url).await.unwrap();
|
||||
crate::runtime::migrations::migrate_runtime_tables(&pool).await.unwrap();
|
||||
assert!(
|
||||
crate::runtime::migrations::migrate_embedding_tables(&pool)
|
||||
.await
|
||||
@@ -125,6 +126,7 @@ async fn setup() -> Option<Fixture> {
|
||||
|
||||
async fn teardown(fixture: &Fixture) {
|
||||
for table in [
|
||||
"runtime_doc_creators",
|
||||
"updates",
|
||||
"snapshot_histories",
|
||||
"snapshots",
|
||||
@@ -514,6 +516,7 @@ async fn doc_append_invalidation_fences_inflight_refresh_and_stamp_covers_redis_
|
||||
fixture.doc_id.clone(),
|
||||
vec![redis_update.into()],
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -554,6 +557,7 @@ async fn doc_append_invalidation_fences_inflight_refresh_and_stamp_covers_redis_
|
||||
fixture.doc_id.clone(),
|
||||
vec![loss_update.into()],
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -119,12 +119,15 @@ async fn load_updates(
|
||||
.map_err(|err| RuntimeError::database("DocCompactor load updates failed", err))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn upsert_snapshot(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &str,
|
||||
doc_id: &str,
|
||||
blob: &[u8],
|
||||
timestamp: DateTime<Utc>,
|
||||
created_at: DateTime<Utc>,
|
||||
updated_at: DateTime<Utc>,
|
||||
creator: Option<&str>,
|
||||
editor: Option<&str>,
|
||||
) -> RuntimeResult<()> {
|
||||
sqlx::query(
|
||||
@@ -132,16 +135,16 @@ async fn upsert_snapshot(
|
||||
INSERT INTO snapshots
|
||||
(workspace_id, guid, blob, size, created_at, updated_at, created_by, updated_by)
|
||||
VALUES
|
||||
($1, $2, $3, $4, $5, $5, $6, $6)
|
||||
($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
ON CONFLICT (workspace_id, guid)
|
||||
DO UPDATE SET
|
||||
blob = $3,
|
||||
size = $4,
|
||||
updated_at = $5,
|
||||
updated_by = $6
|
||||
updated_at = $6,
|
||||
updated_by = $8
|
||||
WHERE snapshots.workspace_id = $1
|
||||
AND snapshots.guid = $2
|
||||
AND snapshots.updated_at <= $5
|
||||
AND snapshots.updated_at <= $6
|
||||
RETURNING updated_at
|
||||
"#,
|
||||
)
|
||||
@@ -149,7 +152,9 @@ async fn upsert_snapshot(
|
||||
.bind(doc_id)
|
||||
.bind(blob)
|
||||
.bind(blob.len() as i64)
|
||||
.bind(timestamp)
|
||||
.bind(created_at)
|
||||
.bind(updated_at)
|
||||
.bind(creator)
|
||||
.bind(editor)
|
||||
.fetch_one(&mut **tx)
|
||||
.await
|
||||
@@ -325,7 +330,52 @@ async fn compact_doc(
|
||||
.filter(|snapshot| snapshot.updated_at > last.created_at)
|
||||
.and_then(|snapshot| snapshot.updated_by.as_deref())
|
||||
.or(last.created_by.as_deref());
|
||||
upsert_snapshot(&mut tx, workspace_id, doc_id, &final_blob, timestamp, editor).await?;
|
||||
if snapshot.is_none() {
|
||||
let first = updates.first().expect("updates is not empty");
|
||||
sqlx::query(
|
||||
"INSERT INTO runtime_doc_creators (workspace_id, doc_id, created_by, created_at) VALUES ($1, $2, $3, $4) ON \
|
||||
CONFLICT (workspace_id, doc_id) DO NOTHING",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
.bind(first.created_by.as_deref())
|
||||
.bind(first.created_at)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("DocCompactor preserve initial doc creator failed", err))?;
|
||||
let creator: Option<String> = sqlx::query_scalar::<_, Option<String>>(
|
||||
"SELECT created_by FROM runtime_doc_creators WHERE workspace_id = $1 AND doc_id = $2",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("DocCompactor load doc creator failed", err))?
|
||||
.flatten();
|
||||
upsert_snapshot(
|
||||
&mut tx,
|
||||
workspace_id,
|
||||
doc_id,
|
||||
&final_blob,
|
||||
first.created_at,
|
||||
timestamp,
|
||||
creator.as_deref(),
|
||||
editor,
|
||||
)
|
||||
.await?;
|
||||
} else {
|
||||
upsert_snapshot(
|
||||
&mut tx,
|
||||
workspace_id,
|
||||
doc_id,
|
||||
&final_blob,
|
||||
timestamp,
|
||||
timestamp,
|
||||
None,
|
||||
editor,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
|
||||
let mut history_created = false;
|
||||
if let Some(snapshot) = &snapshot
|
||||
|
||||
@@ -70,6 +70,57 @@ impl BackendRuntime {
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub async fn get_workspace_doc_creator_v1(
|
||||
&self,
|
||||
workspace_id: String,
|
||||
doc_id: String,
|
||||
) -> napi::Result<Option<String>> {
|
||||
let pool = self.pool().await?;
|
||||
let mut transaction = pool
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("begin document creator read", error))?;
|
||||
lock_current_doc_read(&mut transaction, &workspace_id, &doc_id).await?;
|
||||
let recorded: Option<Option<String>> =
|
||||
sqlx::query_scalar("SELECT created_by FROM runtime_doc_creators WHERE workspace_id=$1 AND doc_id=$2")
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("load runtime document creator", error))?;
|
||||
let creator = if let Some(recorded_creator) = recorded {
|
||||
recorded_creator
|
||||
} else {
|
||||
let has_snapshot: bool =
|
||||
sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM snapshots WHERE workspace_id=$1 AND guid=$2)")
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.fetch_one(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("check document snapshot existence", error))?;
|
||||
if has_snapshot {
|
||||
None
|
||||
} else {
|
||||
sqlx::query_scalar::<_, Option<String>>(
|
||||
"SELECT created_by FROM updates WHERE workspace_id=$1 AND guid=$2 ORDER BY created_at ASC LIMIT 1",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("load initial document update creator", error))?
|
||||
.flatten()
|
||||
}
|
||||
};
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("commit document creator read", error))?;
|
||||
Ok(creator)
|
||||
}
|
||||
|
||||
#[napi]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn upsert_doc_snapshot(
|
||||
&self,
|
||||
workspace_id: String,
|
||||
@@ -77,6 +128,8 @@ impl BackendRuntime {
|
||||
blob: Buffer,
|
||||
timestamp_ms: i64,
|
||||
editor_id: Option<String>,
|
||||
creator_id: Option<String>,
|
||||
from_initial_updates: Option<bool>,
|
||||
) -> napi::Result<bool> {
|
||||
if workspace_id == doc_id {
|
||||
return Err(napi_error("doc_is_workspace"));
|
||||
@@ -91,18 +144,30 @@ impl BackendRuntime {
|
||||
super::domain_command::lock_workspace_storage_shared(&mut transaction, &workspace_id).await?;
|
||||
super::domain_command::lock_workspace_doc_update(&mut transaction, &workspace_id, &doc_id).await?;
|
||||
super::ensure_doc_not_deleted_in(&mut transaction, &workspace_id, &doc_id).await?;
|
||||
let had_snapshot: bool =
|
||||
sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM snapshots WHERE workspace_id = $1 AND guid = $2)")
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.fetch_one(&mut *transaction)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("DocStorage check snapshot existence failed", err))?;
|
||||
let initial_creator = if !had_snapshot && from_initial_updates == Some(true) {
|
||||
creator_id.as_deref()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let row = sqlx::query(
|
||||
r#"
|
||||
INSERT INTO snapshots
|
||||
(workspace_id, guid, blob, size, created_at, updated_at, created_by, updated_by)
|
||||
VALUES
|
||||
($1, $2, $3, $4, $5, $5, $6, $6)
|
||||
($1, $2, $3, $4, $5, $5, $6, $7)
|
||||
ON CONFLICT (workspace_id, guid)
|
||||
DO UPDATE SET
|
||||
blob = $3,
|
||||
size = $4,
|
||||
updated_at = $5,
|
||||
updated_by = $6
|
||||
updated_by = $7
|
||||
WHERE snapshots.workspace_id = $1
|
||||
AND snapshots.guid = $2
|
||||
AND (snapshots.updated_at < $5 OR (snapshots.updated_at = $5 AND snapshots.blob = $3))
|
||||
@@ -114,11 +179,24 @@ impl BackendRuntime {
|
||||
.bind(blob.as_ref())
|
||||
.bind(blob.len() as i64)
|
||||
.bind(timestamp)
|
||||
.bind(initial_creator)
|
||||
.bind(editor_id.as_deref())
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("DocStorage upsert snapshot failed", err))?;
|
||||
if row.is_some() {
|
||||
if !had_snapshot && from_initial_updates == Some(true) {
|
||||
sqlx::query(
|
||||
"INSERT INTO runtime_doc_creators (workspace_id, doc_id, created_by) VALUES ($1, $2, $3) ON CONFLICT \
|
||||
(workspace_id, doc_id) DO NOTHING",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.bind(creator_id.as_deref())
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("DocStorage preserve initial doc creator failed", err))?;
|
||||
}
|
||||
super::domain_command::invalidate_doc_blob_projection(
|
||||
&mut transaction,
|
||||
&workspace_id,
|
||||
@@ -221,7 +299,9 @@ mod tests {
|
||||
workspace_id.clone(),
|
||||
blob.clone().into(),
|
||||
timestamp,
|
||||
None
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
@@ -234,7 +314,9 @@ mod tests {
|
||||
empty_id.clone(),
|
||||
vec![0, 0].into(),
|
||||
timestamp,
|
||||
None
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await?
|
||||
);
|
||||
@@ -245,7 +327,9 @@ mod tests {
|
||||
empty_id.clone(),
|
||||
blob.clone().into(),
|
||||
timestamp,
|
||||
None
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await?
|
||||
);
|
||||
@@ -262,13 +346,23 @@ mod tests {
|
||||
empty_id.clone(),
|
||||
vec![0, 0].into(),
|
||||
timestamp,
|
||||
None
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await?
|
||||
);
|
||||
assert!(
|
||||
runtime
|
||||
.upsert_doc_snapshot(workspace_id.clone(), empty_id, blob.clone().into(), timestamp + 1, None)
|
||||
.upsert_doc_snapshot(
|
||||
workspace_id.clone(),
|
||||
empty_id,
|
||||
blob.clone().into(),
|
||||
timestamp + 1,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await?
|
||||
);
|
||||
let doc_id = "snapshot-doc".to_string();
|
||||
@@ -279,7 +373,9 @@ mod tests {
|
||||
doc_id.clone(),
|
||||
blob.clone().into(),
|
||||
timestamp,
|
||||
None
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await?
|
||||
);
|
||||
@@ -308,6 +404,8 @@ mod tests {
|
||||
blob.clone().into(),
|
||||
timestamp + delta,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(accepted, delta >= 0);
|
||||
@@ -334,4 +432,102 @@ mod tests {
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn upsert_doc_snapshot_does_not_backfill_creator_when_snapshot_exists() -> anyhow::Result<()> {
|
||||
let _guard = DATABASE_TEST_LOCK.lock().await;
|
||||
let Some(runtime) = runtime_from_database_url().await? else {
|
||||
return Ok(());
|
||||
};
|
||||
let pool = runtime.pool().await?;
|
||||
let workspace_id = format!("snapshot-creator-{}", uuid::Uuid::new_v4());
|
||||
let user_a = format!("snap-creator-a-{}", uuid::Uuid::new_v4());
|
||||
let user_b = format!("snap-creator-b-{}", uuid::Uuid::new_v4());
|
||||
for user in [&user_a, &user_b] {
|
||||
sqlx::query(
|
||||
"INSERT INTO users(id,name,email,registered,email_verified,disabled) VALUES($1,$1,$2,true,now(),false)",
|
||||
)
|
||||
.bind(user)
|
||||
.bind(format!("{user}@example.com"))
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
}
|
||||
sqlx::query("INSERT INTO workspaces(id) VALUES($1)")
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
|
||||
let doc_id = "legacy-snapshot-doc".to_string();
|
||||
let timestamp = Utc::now().timestamp_millis();
|
||||
let newer_ts = DateTime::<Utc>::from_timestamp_millis(timestamp + 100).expect("valid timestamp");
|
||||
sqlx::query(
|
||||
"INSERT INTO snapshots(workspace_id,guid,blob,size,created_at,updated_at,created_by,updated_by) \
|
||||
VALUES($1,$2,$3,2,$4,$4,$5,$5)",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.bind(vec![0u8, 0u8])
|
||||
.bind(newer_ts)
|
||||
.bind(&user_b)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
|
||||
// Stale upsert against a newer legacy snapshot: must return false and not
|
||||
// write runtime_doc_creators.
|
||||
let stale_accepted = runtime
|
||||
.upsert_doc_snapshot(
|
||||
workspace_id.clone(),
|
||||
doc_id.clone(),
|
||||
vec![0, 0].into(),
|
||||
timestamp,
|
||||
Some(user_b.clone()),
|
||||
Some(user_a.clone()),
|
||||
Some(true),
|
||||
)
|
||||
.await?;
|
||||
assert!(!stale_accepted);
|
||||
assert_eq!(
|
||||
runtime
|
||||
.get_workspace_doc_creator_v1(workspace_id.clone(), doc_id.clone())
|
||||
.await?,
|
||||
None
|
||||
);
|
||||
|
||||
// Newer upsert against an existing legacy snapshot: must return true but
|
||||
// still not backfill runtime_doc_creators.
|
||||
let newer_accepted = runtime
|
||||
.upsert_doc_snapshot(
|
||||
workspace_id.clone(),
|
||||
doc_id.clone(),
|
||||
vec![0, 0].into(),
|
||||
timestamp + 200,
|
||||
Some(user_b.clone()),
|
||||
Some(user_a.clone()),
|
||||
Some(true),
|
||||
)
|
||||
.await?;
|
||||
assert!(newer_accepted);
|
||||
assert_eq!(
|
||||
runtime
|
||||
.get_workspace_doc_creator_v1(workspace_id.clone(), doc_id.clone())
|
||||
.await?,
|
||||
None
|
||||
);
|
||||
|
||||
for table in ["runtime_doc_creators", "doc_blob_ref_projections", "snapshots"] {
|
||||
sqlx::query(&format!("DELETE FROM {table} WHERE workspace_id=$1"))
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
}
|
||||
sqlx::query("DELETE FROM workspaces WHERE id=$1")
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
sqlx::query("DELETE FROM users WHERE id=ANY($1)")
|
||||
.bind(vec![&user_a, &user_b])
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ use affine_core::access_control::{DomainCommand, classify_reserved_document};
|
||||
use chrono::Duration;
|
||||
use napi::{Result, bindgen_prelude::Buffer};
|
||||
use sqlx::{PgPool, Postgres, Transaction};
|
||||
use y_octo::Update;
|
||||
|
||||
use super::{
|
||||
BackendRuntime, RuntimeError, RuntimeResult, SourceIdentity, blocking,
|
||||
@@ -27,6 +26,7 @@ pub struct AppendWorkspaceDocUpdatesInputV1 {
|
||||
pub write_intent: WorkspaceDocWriteIntentV1,
|
||||
pub expected_permission_generation: Option<i64>,
|
||||
pub protocol_version: Option<u32>,
|
||||
pub expected_current_timestamp: Option<i64>,
|
||||
}
|
||||
|
||||
#[napi_derive::napi(object)]
|
||||
@@ -49,6 +49,7 @@ pub struct AppendWorkspaceDocUpdatesTrustedInputV1 {
|
||||
pub doc_id: String,
|
||||
pub updates: Vec<Buffer>,
|
||||
pub editor_id: Option<String>,
|
||||
pub expected_current_timestamp: Option<i64>,
|
||||
}
|
||||
|
||||
#[napi_derive::napi]
|
||||
@@ -87,11 +88,37 @@ impl BackendRuntime {
|
||||
input.doc_id,
|
||||
input.updates,
|
||||
input.editor_id,
|
||||
input.expected_current_timestamp,
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
async fn ensure_expected_current_timestamp_in(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &str,
|
||||
doc_id: &str,
|
||||
expected_current_timestamp: Option<i64>,
|
||||
) -> Result<()> {
|
||||
let Some(expected_ts) = expected_current_timestamp else {
|
||||
return Ok(());
|
||||
};
|
||||
let max_ts: Option<chrono::DateTime<chrono::Utc>> = sqlx::query_scalar(
|
||||
"SELECT MAX(ts) FROM (SELECT updated_at AS ts FROM snapshots WHERE workspace_id=$1 AND guid=$2 UNION ALL SELECT \
|
||||
created_at AS ts FROM updates WHERE workspace_id=$1 AND guid=$2) AS doc_timestamps",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
.fetch_one(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| napi_error(format!("load current workspace doc timestamp: {error}")))?;
|
||||
let actual_ts = max_ts.map(|t| t.timestamp_millis()).unwrap_or(0);
|
||||
if actual_ts != expected_ts {
|
||||
return Err(napi_error("doc_revision_conflict"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn append_authorized_updates(
|
||||
pool: &PgPool,
|
||||
invalidation: Option<Arc<InvalidationRuntime>>,
|
||||
@@ -114,6 +141,13 @@ async fn append_authorized_updates(
|
||||
lock_workspace_storage_shared(&mut transaction, &input.workspace_id).await?;
|
||||
ensure_workspace_sync_protocol_in(&mut transaction, &input.workspace_id, input.protocol_version).await?;
|
||||
lock_workspace_doc_update(&mut transaction, &input.workspace_id, &input.doc_id).await?;
|
||||
ensure_expected_current_timestamp_in(
|
||||
&mut transaction,
|
||||
&input.workspace_id,
|
||||
&input.doc_id,
|
||||
input.expected_current_timestamp,
|
||||
)
|
||||
.await?;
|
||||
let classification = classify_reserved_document(&input.workspace_id, &input.doc_id);
|
||||
let reserved = input.doc_id == input.workspace_id || classification.is_valid_reserved();
|
||||
let source_exists: bool = sqlx::query_scalar(
|
||||
@@ -191,6 +225,17 @@ async fn append_authorized_updates(
|
||||
)
|
||||
.await?;
|
||||
if creating {
|
||||
sqlx::query(
|
||||
"INSERT INTO runtime_doc_creators (workspace_id, doc_id, created_by, created_at) VALUES ($1, $2, $3, \
|
||||
CURRENT_TIMESTAMP) ON CONFLICT (workspace_id, doc_id) DO UPDATE SET created_by = EXCLUDED.created_by, \
|
||||
created_at = EXCLUDED.created_at",
|
||||
)
|
||||
.bind(&input.workspace_id)
|
||||
.bind(&input.doc_id)
|
||||
.bind(&input.actor_user_id)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| napi_error(format!("record document creator: {error}")))?;
|
||||
invalidate_workspace_inventory_in(&mut transaction, &input.workspace_id).await?;
|
||||
}
|
||||
transaction
|
||||
@@ -204,6 +249,7 @@ async fn append_authorized_updates(
|
||||
})
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) async fn append_updates(
|
||||
pool: &PgPool,
|
||||
invalidation: Option<Arc<InvalidationRuntime>>,
|
||||
@@ -212,6 +258,7 @@ pub(super) async fn append_updates(
|
||||
doc_id: String,
|
||||
updates: Vec<Buffer>,
|
||||
editor_id: Option<String>,
|
||||
expected_current_timestamp: Option<i64>,
|
||||
) -> Result<i64> {
|
||||
if updates.is_empty() {
|
||||
return Ok(0);
|
||||
@@ -223,6 +270,7 @@ pub(super) async fn append_updates(
|
||||
.map_err(|error| napi_error(format!("begin workspace doc update: {error}")))?;
|
||||
lock_workspace_storage_shared(&mut transaction, &workspace_id).await?;
|
||||
lock_workspace_doc_update(&mut transaction, &workspace_id, &doc_id).await?;
|
||||
ensure_expected_current_timestamp_in(&mut transaction, &workspace_id, &doc_id, expected_current_timestamp).await?;
|
||||
ensure_doc_not_deleted_in(&mut transaction, &workspace_id, &doc_id).await?;
|
||||
let source_exists: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM snapshots WHERE workspace_id=$1 AND guid=$2) OR EXISTS(SELECT 1 FROM updates WHERE \
|
||||
@@ -244,6 +292,17 @@ pub(super) async fn append_updates(
|
||||
)
|
||||
.await?;
|
||||
if created {
|
||||
sqlx::query(
|
||||
"INSERT INTO runtime_doc_creators (workspace_id, doc_id, created_by, created_at) VALUES ($1, $2, $3, \
|
||||
CURRENT_TIMESTAMP) ON CONFLICT (workspace_id, doc_id) DO UPDATE SET created_by = EXCLUDED.created_by, \
|
||||
created_at = EXCLUDED.created_at",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.bind(editor_id.as_deref())
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| napi_error(format!("record document creator: {error}")))?;
|
||||
invalidate_workspace_inventory_in(&mut transaction, &workspace_id).await?;
|
||||
}
|
||||
transaction
|
||||
@@ -317,9 +376,7 @@ pub(in crate::runtime) async fn validate_doc_updates(updates: &[Buffer], root: b
|
||||
std::time::Duration::from_secs(1),
|
||||
blocking::spawn(permit, move || {
|
||||
updates.into_iter().try_for_each(|update| {
|
||||
Update::decode_v1(update)
|
||||
.map(|_| ())
|
||||
.map_err(|_| RuntimeError::invalid_input("doc_update_invalid"))
|
||||
y_octo::validate_update_v1(&update).map_err(|_| RuntimeError::invalid_input("doc_update_invalid"))
|
||||
})
|
||||
}),
|
||||
)
|
||||
@@ -431,6 +488,7 @@ mod tests {
|
||||
doc_id: doc_id.clone(),
|
||||
updates: vec![Buffer::from(vec![0, 0]), Buffer::from(vec![0xff])],
|
||||
editor_id: None,
|
||||
expected_current_timestamp: None,
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
@@ -449,6 +507,7 @@ mod tests {
|
||||
doc_id: doc_id.clone(),
|
||||
updates: vec![Buffer::from(vec![0, 0]), Buffer::from(vec![0, 0])],
|
||||
editor_id: None,
|
||||
expected_current_timestamp: None,
|
||||
})
|
||||
.await
|
||||
.map_err(|error| anyhow::anyhow!(error.to_string()))?;
|
||||
@@ -458,6 +517,7 @@ mod tests {
|
||||
doc_id: doc_id.clone(),
|
||||
updates: vec![Buffer::from(vec![0, 0])],
|
||||
editor_id: None,
|
||||
expected_current_timestamp: None,
|
||||
})
|
||||
.await
|
||||
.map_err(|error| anyhow::anyhow!(error.to_string()))?;
|
||||
@@ -508,6 +568,7 @@ mod tests {
|
||||
|
||||
protocol_version: None,
|
||||
expected_permission_generation: Some(generation),
|
||||
expected_current_timestamp: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
@@ -529,6 +590,7 @@ mod tests {
|
||||
|
||||
protocol_version: None,
|
||||
expected_permission_generation: None,
|
||||
expected_current_timestamp: None,
|
||||
})
|
||||
.await;
|
||||
assert!(
|
||||
@@ -627,6 +689,7 @@ mod tests {
|
||||
|
||||
protocol_version: None,
|
||||
expected_permission_generation: Some(generation),
|
||||
expected_current_timestamp: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
@@ -655,6 +718,7 @@ mod tests {
|
||||
|
||||
protocol_version: None,
|
||||
expected_permission_generation: None,
|
||||
expected_current_timestamp: None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(result.is_ok(), allowed, "{reserved_doc_id}: {result:?}");
|
||||
@@ -670,6 +734,7 @@ mod tests {
|
||||
|
||||
protocol_version: None,
|
||||
expected_permission_generation: None,
|
||||
expected_current_timestamp: None,
|
||||
};
|
||||
sqlx::query(
|
||||
"DELETE FROM storage_reconciliation_checkpoints WHERE kind='workspace_doc_lifecycle_activation' AND \
|
||||
@@ -917,7 +982,8 @@ mod tests {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: creating_doc_id.clone(),
|
||||
updates: vec![Buffer::from(vec![0, 0])],
|
||||
editor_id: Some(user_id.clone())
|
||||
editor_id: Some(user_id.clone()),
|
||||
expected_current_timestamp: None,
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
@@ -929,7 +995,9 @@ mod tests {
|
||||
creating_doc_id.clone(),
|
||||
Buffer::from(vec![0, 0, 0]),
|
||||
chrono::Utc::now().timestamp_millis(),
|
||||
None
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
@@ -1150,4 +1218,459 @@ mod tests {
|
||||
.map_err(|error| anyhow::anyhow!(error.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn append_enforces_expected_current_timestamp_cas() -> anyhow::Result<()> {
|
||||
let _guard = pg_test_lock().lock().await;
|
||||
let Some(runtime) = runtime_from_database_url().await? else {
|
||||
return Ok(());
|
||||
};
|
||||
let suffix = Uuid::new_v4().simple().to_string();
|
||||
let workspace_id = format!("doc-writer-cas-ws-{suffix}");
|
||||
let user_id = format!("doc-writer-cas-user-{suffix}");
|
||||
let pool = runtime
|
||||
.pool()
|
||||
.await
|
||||
.map_err(|error| anyhow::anyhow!(error.to_string()))?;
|
||||
sqlx::query("INSERT INTO workspaces(id) VALUES($1)")
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO users(id,name,email,registered,email_verified,disabled) VALUES($1,'CAS Writer',$2,true,now(),false)",
|
||||
)
|
||||
.bind(&user_id)
|
||||
.bind(format!("doc-writer-cas-{suffix}@example.com"))
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
sqlx::query("INSERT INTO workspace_access_policies(workspace_id) VALUES($1)")
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
sqlx::query("INSERT INTO workspace_members(workspace_id,user_id,role,state) VALUES($1,$2,'owner','active')")
|
||||
.bind(&workspace_id)
|
||||
.bind(&user_id)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
|
||||
// Empty root doc has actual timestamp 0 -> mismatch must conflict without
|
||||
// writing.
|
||||
let mismatch_empty = runtime
|
||||
.append_workspace_doc_updates_v1(AppendWorkspaceDocUpdatesInputV1 {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: workspace_id.clone(),
|
||||
updates: vec![Buffer::from(vec![0, 0])],
|
||||
actor_user_id: user_id.clone(),
|
||||
write_intent: WorkspaceDocWriteIntentV1::UpdateDoc,
|
||||
expected_permission_generation: None,
|
||||
protocol_version: None,
|
||||
expected_current_timestamp: Some(12345),
|
||||
})
|
||||
.await;
|
||||
assert!(
|
||||
mismatch_empty
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("doc_revision_conflict")
|
||||
);
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>("SELECT count(*) FROM updates WHERE workspace_id=$1 AND guid=$2")
|
||||
.bind(&workspace_id)
|
||||
.bind(&workspace_id)
|
||||
.fetch_one(&pool)
|
||||
.await?,
|
||||
0
|
||||
);
|
||||
|
||||
// Matching expected_current_timestamp = 0 succeeds.
|
||||
let first = runtime
|
||||
.append_workspace_doc_updates_v1(AppendWorkspaceDocUpdatesInputV1 {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: workspace_id.clone(),
|
||||
updates: vec![Buffer::from(vec![0, 0])],
|
||||
actor_user_id: user_id.clone(),
|
||||
write_intent: WorkspaceDocWriteIntentV1::UpdateDoc,
|
||||
expected_permission_generation: None,
|
||||
protocol_version: None,
|
||||
expected_current_timestamp: Some(0),
|
||||
})
|
||||
.await
|
||||
.map_err(|error| anyhow::anyhow!(error.to_string()))?;
|
||||
assert!(first.timestamp > 0);
|
||||
|
||||
// Stale expected_current_timestamp = 0 now conflicts without writing.
|
||||
let stale = runtime
|
||||
.append_workspace_doc_updates_v1(AppendWorkspaceDocUpdatesInputV1 {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: workspace_id.clone(),
|
||||
updates: vec![Buffer::from(vec![0, 0])],
|
||||
actor_user_id: user_id.clone(),
|
||||
write_intent: WorkspaceDocWriteIntentV1::UpdateDoc,
|
||||
expected_permission_generation: None,
|
||||
protocol_version: None,
|
||||
expected_current_timestamp: Some(0),
|
||||
})
|
||||
.await;
|
||||
assert!(stale.unwrap_err().to_string().contains("doc_revision_conflict"));
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>("SELECT count(*) FROM updates WHERE workspace_id=$1 AND guid=$2")
|
||||
.bind(&workspace_id)
|
||||
.bind(&workspace_id)
|
||||
.fetch_one(&pool)
|
||||
.await?,
|
||||
1
|
||||
);
|
||||
|
||||
// Matching current timestamp succeeds.
|
||||
let second = runtime
|
||||
.append_workspace_doc_updates_v1(AppendWorkspaceDocUpdatesInputV1 {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: workspace_id.clone(),
|
||||
updates: vec![Buffer::from(vec![0, 0])],
|
||||
actor_user_id: user_id.clone(),
|
||||
write_intent: WorkspaceDocWriteIntentV1::UpdateDoc,
|
||||
expected_permission_generation: None,
|
||||
protocol_version: None,
|
||||
expected_current_timestamp: Some(first.timestamp),
|
||||
})
|
||||
.await
|
||||
.map_err(|error| anyhow::anyhow!(error.to_string()))?;
|
||||
assert!(second.timestamp > first.timestamp);
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>("SELECT count(*) FROM updates WHERE workspace_id=$1 AND guid=$2")
|
||||
.bind(&workspace_id)
|
||||
.bind(&workspace_id)
|
||||
.fetch_one(&pool)
|
||||
.await?,
|
||||
2
|
||||
);
|
||||
|
||||
// Trusted append also enforces expected_current_timestamp CAS.
|
||||
let props_doc_id = format!("db${workspace_id}$docProperties");
|
||||
let trusted_first = runtime
|
||||
.append_workspace_doc_updates_trusted_v1(AppendWorkspaceDocUpdatesTrustedInputV1 {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: props_doc_id.clone(),
|
||||
updates: vec![Buffer::from(vec![0, 0])],
|
||||
editor_id: Some(user_id.clone()),
|
||||
expected_current_timestamp: Some(0),
|
||||
})
|
||||
.await
|
||||
.map_err(|error| anyhow::anyhow!(error.to_string()))?;
|
||||
assert!(trusted_first > 0);
|
||||
|
||||
let trusted_stale = runtime
|
||||
.append_workspace_doc_updates_trusted_v1(AppendWorkspaceDocUpdatesTrustedInputV1 {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: props_doc_id.clone(),
|
||||
updates: vec![Buffer::from(vec![0, 0])],
|
||||
editor_id: Some(user_id.clone()),
|
||||
expected_current_timestamp: Some(0),
|
||||
})
|
||||
.await;
|
||||
assert!(trusted_stale.unwrap_err().to_string().contains("doc_revision_conflict"));
|
||||
let trusted_second = runtime
|
||||
.append_workspace_doc_updates_trusted_v1(AppendWorkspaceDocUpdatesTrustedInputV1 {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: props_doc_id.clone(),
|
||||
updates: vec![Buffer::from(vec![0, 0])],
|
||||
editor_id: Some(user_id.clone()),
|
||||
expected_current_timestamp: Some(trusted_first),
|
||||
})
|
||||
.await
|
||||
.map_err(|error| anyhow::anyhow!(error.to_string()))?;
|
||||
assert!(trusted_second > trusted_first);
|
||||
|
||||
sqlx::query("DELETE FROM runtime_doc_creators WHERE workspace_id=$1")
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
sqlx::query("DELETE FROM workspaces WHERE id=$1")
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
runtime
|
||||
.stop()
|
||||
.await
|
||||
.map_err(|error| anyhow::anyhow!(error.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn doc_creator_survives_first_compaction_and_owner_transfer_and_legacy_snapshot_is_none() -> anyhow::Result<()>
|
||||
{
|
||||
let _guard = crate::runtime::migrations::DATABASE_TEST_LOCK.lock().await;
|
||||
let Some(runtime) = runtime_from_database_url().await? else {
|
||||
return Ok(());
|
||||
};
|
||||
let pool = runtime.pool().await?;
|
||||
let workspace_id = format!("doc-creator-ws-{}", uuid::Uuid::new_v4());
|
||||
let user_a = format!("doc-creator-a-{}", uuid::Uuid::new_v4());
|
||||
let user_b = format!("doc-creator-b-{}", uuid::Uuid::new_v4());
|
||||
let user_c = format!("doc-creator-c-{}", uuid::Uuid::new_v4());
|
||||
for user in [&user_a, &user_b, &user_c] {
|
||||
sqlx::query(
|
||||
"INSERT INTO users(id,name,email,registered,email_verified,disabled) VALUES($1,$1,$2,true,now(),false)",
|
||||
)
|
||||
.bind(user)
|
||||
.bind(format!("{user}@example.com"))
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
}
|
||||
sqlx::query("INSERT INTO workspaces(id) VALUES($1)")
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
sqlx::query("INSERT INTO workspace_access_policies(workspace_id,member_default_doc_role) VALUES($1,'editor')")
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
for (user, role) in [(&user_a, "member"), (&user_b, "member"), (&user_c, "owner")] {
|
||||
sqlx::query("INSERT INTO workspace_members(workspace_id,user_id,role,state) VALUES($1,$2,$3,'active')")
|
||||
.bind(&workspace_id)
|
||||
.bind(user)
|
||||
.bind(role)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
}
|
||||
|
||||
// Case A1: Pre-existing uncompacted updates (no runtime_doc_creators row
|
||||
// before compaction): A creates, B edits.
|
||||
let pre_doc = "doc-pre-updates".to_string();
|
||||
let now = chrono::Utc::now();
|
||||
sqlx::query("INSERT INTO updates(workspace_id,guid,blob,created_at,created_by) VALUES($1,$2,$3,$4,$5)")
|
||||
.bind(&workspace_id)
|
||||
.bind(&pre_doc)
|
||||
.bind(vec![0u8, 0u8])
|
||||
.bind(now)
|
||||
.bind(&user_a)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
sqlx::query("INSERT INTO updates(workspace_id,guid,blob,created_at,created_by) VALUES($1,$2,$3,$4,$5)")
|
||||
.bind(&workspace_id)
|
||||
.bind(&pre_doc)
|
||||
.bind(vec![0u8, 0u8])
|
||||
.bind(now + Duration::milliseconds(10))
|
||||
.bind(&user_b)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
runtime
|
||||
.get_workspace_doc_creator_v1(workspace_id.clone(), pre_doc.clone())
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!(e.to_string()))?,
|
||||
Some(user_a.clone())
|
||||
);
|
||||
// Transfer owner grant to C before compaction; creator must still be A.
|
||||
sqlx::query(
|
||||
"INSERT INTO doc_grants(workspace_id,doc_id,principal_type,principal_id,role,granted_by) \
|
||||
VALUES($1,$2,'user',$3,'owner',$3)",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&pre_doc)
|
||||
.bind(&user_c)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
|
||||
runtime
|
||||
.compact_pending_doc_updates(workspace_id.clone(), pre_doc.clone(), 100, 60_000, 3600)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!(e.to_string()))?;
|
||||
|
||||
let (snap_creator, snap_editor): (Option<String>, Option<String>) =
|
||||
sqlx::query_as("SELECT created_by, updated_by FROM snapshots WHERE workspace_id=$1 AND guid=$2")
|
||||
.bind(&workspace_id)
|
||||
.bind(&pre_doc)
|
||||
.fetch_one(&pool)
|
||||
.await?;
|
||||
assert_eq!(snap_creator.as_deref(), Some(user_a.as_str()));
|
||||
assert_eq!(snap_editor.as_deref(), Some(user_b.as_str()));
|
||||
let current = runtime
|
||||
.get_current_workspace_doc_v1(workspace_id.clone(), pre_doc.clone())
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!(e.to_string()))?
|
||||
.expect("doc exists");
|
||||
assert_eq!(current.editor.as_deref(), Some(user_b.as_str()));
|
||||
assert_eq!(
|
||||
runtime
|
||||
.get_workspace_doc_creator_v1(workspace_id.clone(), pre_doc.clone())
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!(e.to_string()))?,
|
||||
Some(user_a.clone())
|
||||
);
|
||||
|
||||
// Case A2: Formal CreateDoc path -> B edit -> owner grant transfer to C ->
|
||||
// first compaction.
|
||||
let new_doc = "doc-formal-create".to_string();
|
||||
runtime
|
||||
.append_workspace_doc_updates_v1(AppendWorkspaceDocUpdatesInputV1 {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: new_doc.clone(),
|
||||
updates: vec![Buffer::from(vec![0, 0])],
|
||||
actor_user_id: user_a.clone(),
|
||||
write_intent: WorkspaceDocWriteIntentV1::CreateDoc,
|
||||
expected_permission_generation: None,
|
||||
protocol_version: None,
|
||||
expected_current_timestamp: None,
|
||||
})
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!(e.to_string()))?;
|
||||
runtime
|
||||
.append_workspace_doc_updates_v1(AppendWorkspaceDocUpdatesInputV1 {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: new_doc.clone(),
|
||||
updates: vec![Buffer::from(vec![0, 0])],
|
||||
actor_user_id: user_b.clone(),
|
||||
write_intent: WorkspaceDocWriteIntentV1::UpdateDoc,
|
||||
expected_permission_generation: None,
|
||||
protocol_version: None,
|
||||
expected_current_timestamp: None,
|
||||
})
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!(e.to_string()))?;
|
||||
sqlx::query("DELETE FROM doc_grants WHERE workspace_id=$1 AND doc_id=$2")
|
||||
.bind(&workspace_id)
|
||||
.bind(&new_doc)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO doc_grants(workspace_id,doc_id,principal_type,principal_id,role,granted_by) \
|
||||
VALUES($1,$2,'user',$3,'owner',$3)",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&new_doc)
|
||||
.bind(&user_c)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
runtime
|
||||
.compact_pending_doc_updates(workspace_id.clone(), new_doc.clone(), 100, 60_000, 3600)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!(e.to_string()))?;
|
||||
let (new_snap_creator, new_snap_editor): (Option<String>, Option<String>) =
|
||||
sqlx::query_as("SELECT created_by, updated_by FROM snapshots WHERE workspace_id=$1 AND guid=$2")
|
||||
.bind(&workspace_id)
|
||||
.bind(&new_doc)
|
||||
.fetch_one(&pool)
|
||||
.await?;
|
||||
assert_eq!(new_snap_creator.as_deref(), Some(user_a.as_str()));
|
||||
assert_eq!(new_snap_editor.as_deref(), Some(user_b.as_str()));
|
||||
assert_eq!(
|
||||
runtime
|
||||
.get_workspace_doc_creator_v1(workspace_id.clone(), new_doc.clone())
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!(e.to_string()))?,
|
||||
Some(user_a.clone())
|
||||
);
|
||||
|
||||
// Case B: Legacy snapshot without runtime_doc_creators row returns None
|
||||
// even with snapshots.created_by and doc_grants.
|
||||
let legacy_doc = "doc-legacy-snapshot".to_string();
|
||||
sqlx::query(
|
||||
"INSERT INTO snapshots(workspace_id,guid,blob,size,created_at,updated_at,created_by,updated_by) \
|
||||
VALUES($1,$2,$3,2,now(),now(),$4,$4)",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&legacy_doc)
|
||||
.bind(vec![0u8, 0u8])
|
||||
.bind(&user_b)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO doc_grants(workspace_id,doc_id,principal_type,principal_id,role,granted_by) \
|
||||
VALUES($1,$2,'user',$3,'owner',$3)",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&legacy_doc)
|
||||
.bind(&user_c)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
runtime
|
||||
.get_workspace_doc_creator_v1(workspace_id.clone(), legacy_doc.clone())
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!(e.to_string()))?,
|
||||
None
|
||||
);
|
||||
|
||||
// Case C: Author A creates doc, B edits, then A's user account is deleted
|
||||
// before first compaction (FK ON DELETE SET NULL clears both
|
||||
// updates.created_by and runtime_doc_creators.created_by); first compaction
|
||||
// must succeed cleanly.
|
||||
let deleted_author_doc = "doc-deleted-author".to_string();
|
||||
runtime
|
||||
.append_workspace_doc_updates_v1(AppendWorkspaceDocUpdatesInputV1 {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: deleted_author_doc.clone(),
|
||||
updates: vec![Buffer::from(vec![0, 0])],
|
||||
actor_user_id: user_a.clone(),
|
||||
write_intent: WorkspaceDocWriteIntentV1::CreateDoc,
|
||||
expected_permission_generation: None,
|
||||
protocol_version: None,
|
||||
expected_current_timestamp: None,
|
||||
})
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!(e.to_string()))?;
|
||||
runtime
|
||||
.append_workspace_doc_updates_v1(AppendWorkspaceDocUpdatesInputV1 {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: deleted_author_doc.clone(),
|
||||
updates: vec![Buffer::from(vec![0, 0])],
|
||||
actor_user_id: user_b.clone(),
|
||||
write_intent: WorkspaceDocWriteIntentV1::UpdateDoc,
|
||||
expected_permission_generation: None,
|
||||
protocol_version: None,
|
||||
expected_current_timestamp: None,
|
||||
})
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!(e.to_string()))?;
|
||||
sqlx::query("DELETE FROM users WHERE id=$1")
|
||||
.bind(&user_a)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
runtime
|
||||
.compact_pending_doc_updates(workspace_id.clone(), deleted_author_doc.clone(), 100, 60_000, 3600)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!(e.to_string()))?;
|
||||
assert_eq!(
|
||||
runtime
|
||||
.get_workspace_doc_creator_v1(workspace_id.clone(), deleted_author_doc.clone())
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!(e.to_string()))?,
|
||||
None
|
||||
);
|
||||
let deleted_author_current = runtime
|
||||
.get_current_workspace_doc_v1(workspace_id.clone(), deleted_author_doc.clone())
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!(e.to_string()))?
|
||||
.expect("doc exists after compaction");
|
||||
assert_eq!(deleted_author_current.editor.as_deref(), Some(user_b.as_str()));
|
||||
let (del_snap_creator, del_snap_editor): (Option<String>, Option<String>) =
|
||||
sqlx::query_as("SELECT created_by, updated_by FROM snapshots WHERE workspace_id=$1 AND guid=$2")
|
||||
.bind(&workspace_id)
|
||||
.bind(&deleted_author_doc)
|
||||
.fetch_one(&pool)
|
||||
.await?;
|
||||
assert_eq!(del_snap_creator, None);
|
||||
assert_eq!(del_snap_editor.as_deref(), Some(user_b.as_str()));
|
||||
|
||||
for table in ["runtime_doc_creators", "doc_grants", "updates", "snapshots"] {
|
||||
sqlx::query(&format!("DELETE FROM {table} WHERE workspace_id=$1"))
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
}
|
||||
sqlx::query("DELETE FROM workspaces WHERE id=$1")
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
sqlx::query("DELETE FROM users WHERE id=ANY($1)")
|
||||
.bind(vec![&user_a, &user_b, &user_c])
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
runtime
|
||||
.stop()
|
||||
.await
|
||||
.map_err(|error| anyhow::anyhow!(error.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -221,6 +221,7 @@ async fn delete_doc_rows(
|
||||
("comments", "doc_id"),
|
||||
("doc_blob_refs", "doc_id"),
|
||||
("doc_blob_ref_projections", "doc_id"),
|
||||
("runtime_doc_creators", "doc_id"),
|
||||
("ai_workspace_ignored_docs", "doc_id"),
|
||||
("workspace_doc_view_daily", "doc_id"),
|
||||
("doc_grants", "doc_id"),
|
||||
|
||||
@@ -242,3 +242,22 @@ CREATE TABLE IF NOT EXISTS runtime_invite_abuse_actions (
|
||||
|
||||
CREATE INDEX IF NOT EXISTS runtime_invite_abuse_actions_status_next_attempt_idx
|
||||
ON runtime_invite_abuse_actions (status, next_attempt_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS runtime_doc_creators (
|
||||
workspace_id VARCHAR NOT NULL,
|
||||
doc_id VARCHAR NOT NULL,
|
||||
created_by VARCHAR REFERENCES users(id) ON DELETE SET NULL ON UPDATE CASCADE,
|
||||
created_at TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (workspace_id, doc_id)
|
||||
);
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint WHERE conname = 'runtime_doc_creators_created_by_fkey'
|
||||
) THEN
|
||||
ALTER TABLE runtime_doc_creators
|
||||
ADD CONSTRAINT runtime_doc_creators_created_by_fkey
|
||||
FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
END IF;
|
||||
END $$;
|
||||
@@ -595,6 +595,7 @@ mod tests {
|
||||
"blob_cleanup_candidates",
|
||||
"doc_blob_refs",
|
||||
"doc_blob_ref_projections",
|
||||
"runtime_doc_creators",
|
||||
"updates",
|
||||
"snapshot_histories",
|
||||
"snapshots",
|
||||
|
||||
@@ -581,6 +581,7 @@ mod tests {
|
||||
"embedding_indexes",
|
||||
"doc_blob_refs",
|
||||
"doc_blob_ref_projections",
|
||||
"runtime_doc_creators",
|
||||
"document_cleanup_candidates",
|
||||
"blob_cleanup_candidates",
|
||||
"storage_reconciliation_runs",
|
||||
@@ -609,6 +610,7 @@ mod tests {
|
||||
"INSERT INTO doc_blob_refs(workspace_id,doc_id,blob_key,block_id,flavour,snapshot_updated_at,parser_version) \
|
||||
VALUES($1,'doc','blob','block','affine:attachment',now(),1)",
|
||||
"INSERT INTO doc_blob_ref_projections(workspace_id,doc_id,parser_version,status) VALUES($1,'doc',1,'pending')",
|
||||
"INSERT INTO runtime_doc_creators(workspace_id,doc_id,created_by) VALUES($1,'doc',NULL)",
|
||||
"INSERT INTO document_cleanup_candidates(workspace_id,doc_id,status,missing_since,last_observed_missing_at) \
|
||||
VALUES($1,'doc','marked',now(),now())",
|
||||
"INSERT INTO blob_cleanup_candidates(workspace_id,blob_key,reason,status,object_size,run_id) \
|
||||
@@ -835,6 +837,7 @@ mod tests {
|
||||
"embedding_sources",
|
||||
"embedding_workspace_states",
|
||||
"embedding_indexes",
|
||||
"runtime_doc_creators",
|
||||
"blob_cleanup_candidates",
|
||||
"storage_reconciliation_runs",
|
||||
"storage_reconciliation_checkpoints",
|
||||
|
||||
@@ -114,6 +114,7 @@ const WORKSPACE_STORAGE_TABLES: &[&str] = &[
|
||||
"snapshot_histories",
|
||||
"doc_blob_refs",
|
||||
"doc_blob_ref_projections",
|
||||
"runtime_doc_creators",
|
||||
"document_cleanup_candidates",
|
||||
"blob_cleanup_candidates",
|
||||
"storage_reconciliation_runs",
|
||||
|
||||
@@ -108,7 +108,6 @@
|
||||
"socket.io": "^4.8.3",
|
||||
"tldts": "^7.0.19",
|
||||
"winston": "^3.17.0",
|
||||
"yjs": "^13.6.27",
|
||||
"zod": "^3.25.76",
|
||||
"zod-to-json-schema": "^3.20.0"
|
||||
},
|
||||
@@ -143,7 +142,8 @@
|
||||
"sinon": "^21.0.1",
|
||||
"socket.io-client": "^4.8.3",
|
||||
"supertest": "^7.1.4",
|
||||
"typescript": "npm:@typescript/typescript6@6.0.2"
|
||||
"typescript": "npm:@typescript/typescript6@6.0.2",
|
||||
"yjs": "^13.6.27"
|
||||
},
|
||||
"nodemonConfig": {
|
||||
"exec": "node",
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
DocStorageModule,
|
||||
PgUserspaceDocStorageAdapter as Adapter,
|
||||
} from '../../core/doc';
|
||||
import { mergeUpdatesWithYjs } from '../../core/doc/merge-updates';
|
||||
import { mergeUpdatesWithNative } from '../../core/doc/merge-updates';
|
||||
import { Models, type User } from '../../models';
|
||||
import { createTestingModule, type TestingModule } from '../utils';
|
||||
|
||||
@@ -79,7 +79,7 @@ test('should push user doc updates work', async t => {
|
||||
t.deepEqual(Buffer.from(unchanged!.bin), Buffer.from(record!.bin));
|
||||
t.is(unchanged!.timestamp, record!.timestamp);
|
||||
t.throws(() =>
|
||||
mergeUpdatesWithYjs(
|
||||
mergeUpdatesWithNative(
|
||||
[...Array.from({ length: 10 }, () => updates[0]), new Uint8Array([255])],
|
||||
'userspace.invalid_later_batch'
|
||||
)
|
||||
|
||||
@@ -401,3 +401,103 @@ test('should not recreate a doc deleted before its read acquires the database lo
|
||||
t.is(await db.snapshot.count({ where: { workspaceId, id: docId } }), 0);
|
||||
t.is(await db.update.count({ where: { workspaceId, id: docId } }), 0);
|
||||
});
|
||||
|
||||
test('recoverDocCreation preserves initial creator across first compaction and leaves legacy snapshot createdBy unset', async t => {
|
||||
const workspaceId = 'recover-creator-pg';
|
||||
const userA = 'user-author-a';
|
||||
const userB = 'user-editor-b';
|
||||
const collaborator = 'user-collab-c';
|
||||
|
||||
await db.user.createMany({
|
||||
data: [
|
||||
{ id: userA, name: 'Author A', email: 'author-a@affine.pro' },
|
||||
{ id: userB, name: 'Editor B', email: 'editor-b@affine.pro' },
|
||||
{ id: collaborator, name: 'Collab C', email: 'collab-c@affine.pro' },
|
||||
],
|
||||
});
|
||||
|
||||
await db.workspace.create({
|
||||
data: {
|
||||
id: workspaceId,
|
||||
accessPolicy: { create: { memberDefaultDocRole: 'editor' } },
|
||||
},
|
||||
});
|
||||
|
||||
const mode = Sinon.stub(runtime, 'getWorkspaceLifecycleActiveV1').resolves(
|
||||
true
|
||||
);
|
||||
t.teardown(() => mode.restore());
|
||||
const writer = new DocWriter(adapter, m.get(EventBus), runtime);
|
||||
|
||||
// 1. Pre-existing uncompacted updates: userA creates, userB edits -> first compaction -> recoverDocCreation.
|
||||
const docId = 'doc-uncompacted-a-b';
|
||||
const initialBin = createDocWithMarkdown('Title A', 'Body A', docId, {
|
||||
actorUserId: userA,
|
||||
timestampMs: Date.now(),
|
||||
});
|
||||
const baseTs = Date.now();
|
||||
await db.update.create({
|
||||
data: {
|
||||
workspaceId,
|
||||
id: docId,
|
||||
blob: Buffer.from(initialBin),
|
||||
createdAt: new Date(baseTs),
|
||||
createdBy: userA,
|
||||
},
|
||||
});
|
||||
await db.update.create({
|
||||
data: {
|
||||
workspaceId,
|
||||
id: docId,
|
||||
blob: Buffer.from([0, 0]),
|
||||
createdAt: new Date(baseTs + 10),
|
||||
createdBy: userB,
|
||||
},
|
||||
});
|
||||
|
||||
await runtime.compactPendingDocUpdates(workspaceId, docId, 100, 60_000, 3600);
|
||||
await writer.recoverDocCreation(workspaceId, docId, 'Fallback', collaborator);
|
||||
|
||||
const propsDocId = `db$${workspaceId}$docProperties`;
|
||||
const propsAfterFirst = await adapter.getDoc(workspaceId, propsDocId);
|
||||
t.truthy(propsAfterFirst?.bin);
|
||||
const propsYdoc1 = new YDoc();
|
||||
applyUpdate(propsYdoc1, propsAfterFirst!.bin);
|
||||
t.is(propsYdoc1.getMap(docId).get('createdBy'), userA);
|
||||
t.is(propsYdoc1.getMap(docId).get('updatedBy'), userB);
|
||||
propsYdoc1.destroy();
|
||||
|
||||
// 2. Legacy snapshot-only doc (no runtime_doc_creators row): createdBy stays undefined, updatedBy is userB.
|
||||
const legacyDocId = 'doc-legacy-snap-only';
|
||||
const legacyBin = createDocWithMarkdown('Legacy Title', 'Body', legacyDocId, {
|
||||
actorUserId: userB,
|
||||
timestampMs: Date.now(),
|
||||
});
|
||||
await db.snapshot.create({
|
||||
data: {
|
||||
workspaceId,
|
||||
id: legacyDocId,
|
||||
blob: Buffer.from(legacyBin),
|
||||
size: legacyBin.byteLength,
|
||||
createdAt: new Date(baseTs),
|
||||
updatedAt: new Date(baseTs),
|
||||
createdBy: userB,
|
||||
updatedBy: userB,
|
||||
},
|
||||
});
|
||||
|
||||
await writer.recoverDocCreation(
|
||||
workspaceId,
|
||||
legacyDocId,
|
||||
'Fallback',
|
||||
collaborator
|
||||
);
|
||||
|
||||
const propsAfterLegacy = await adapter.getDoc(workspaceId, propsDocId);
|
||||
t.truthy(propsAfterLegacy?.bin);
|
||||
const propsYdoc2 = new YDoc();
|
||||
applyUpdate(propsYdoc2, propsAfterLegacy!.bin);
|
||||
t.is(propsYdoc2.getMap(legacyDocId).get('createdBy'), undefined);
|
||||
t.is(propsYdoc2.getMap(legacyDocId).get('updatedBy'), userB);
|
||||
propsYdoc2.destroy();
|
||||
});
|
||||
@@ -0,0 +1,875 @@
|
||||
import { McpAccessMode } from '@prisma/client';
|
||||
import test from 'ava';
|
||||
import {
|
||||
applyUpdate,
|
||||
Array as YArray,
|
||||
Doc as YDoc,
|
||||
encodeStateAsUpdate,
|
||||
Map as YMap,
|
||||
} from 'yjs';
|
||||
|
||||
import { DocCreateIncompleteError, DocWriter } from '../../core/doc/writer';
|
||||
import {
|
||||
createDocWithMarkdown,
|
||||
extractWorkspaceLifecycleRootPages,
|
||||
mergeUpdates,
|
||||
updateDocProperties,
|
||||
} from '../../native';
|
||||
import { WorkspaceMcpProvider } from '../../plugins/copilot/mcp/provider';
|
||||
import { executeToolCall } from '../../plugins/copilot/runtime/tool/bridge';
|
||||
import {
|
||||
buildDocCreateHandler,
|
||||
createDocCreateTool,
|
||||
} from '../../plugins/copilot/tools/doc-write';
|
||||
|
||||
function createLegacyArrayRootDoc(pages: Array<Record<string, unknown>>) {
|
||||
const doc = new YDoc();
|
||||
doc.getMap('meta').set('pages', pages);
|
||||
return Buffer.from(encodeStateAsUpdate(doc));
|
||||
}
|
||||
|
||||
function createWriterHarness(
|
||||
initialDocs: Map<string, Uint8Array>,
|
||||
options?: {
|
||||
initialEditors?: Map<string, string>;
|
||||
initialCreators?: Map<string, string>;
|
||||
onBeforePush?: (params: {
|
||||
workspaceId: string;
|
||||
docId: string;
|
||||
updates: Uint8Array[];
|
||||
expectedCurrentTimestamp?: number;
|
||||
}) => Promise<void> | void;
|
||||
}
|
||||
) {
|
||||
const pushed: Array<{
|
||||
docId: string;
|
||||
updates: Uint8Array[];
|
||||
editor?: string;
|
||||
}> = [];
|
||||
const emitted: Array<{ docId: string; updates: Uint8Array[] }> = [];
|
||||
const timestamps = new Map<string, number>();
|
||||
const editors = new Map<string, string>(options?.initialEditors);
|
||||
const creators = new Map<string, string>(options?.initialCreators);
|
||||
let clock = 1000;
|
||||
for (const docId of initialDocs.keys()) {
|
||||
timestamps.set(docId, clock);
|
||||
}
|
||||
|
||||
const storage = {
|
||||
isEmptyBin(bin: Uint8Array) {
|
||||
return (
|
||||
bin.length === 0 ||
|
||||
(bin.length === 1 && bin[0] === 0) ||
|
||||
(bin.length === 2 && bin[0] === 0 && bin[1] === 0)
|
||||
);
|
||||
},
|
||||
async getDoc(_workspaceId: string, docId: string) {
|
||||
const bin = initialDocs.get(docId);
|
||||
if (!bin) return null;
|
||||
return {
|
||||
spaceId: _workspaceId,
|
||||
docId,
|
||||
bin,
|
||||
timestamp: timestamps.get(docId) ?? 0,
|
||||
editor: editors.get(docId),
|
||||
creator: creators.get(docId),
|
||||
};
|
||||
},
|
||||
async pushDocUpdates(
|
||||
workspaceId: string,
|
||||
docId: string,
|
||||
updates: Uint8Array[],
|
||||
editorId?: string,
|
||||
_expectedPermissionGeneration?: number,
|
||||
_writeIntent?: 'update_doc' | 'create_doc',
|
||||
_protocolVersion?: number,
|
||||
expectedCurrentTimestamp?: number
|
||||
) {
|
||||
await options?.onBeforePush?.({
|
||||
workspaceId,
|
||||
docId,
|
||||
updates,
|
||||
expectedCurrentTimestamp,
|
||||
});
|
||||
const currentTs = timestamps.get(docId) ?? 0;
|
||||
if (
|
||||
expectedCurrentTimestamp !== undefined &&
|
||||
currentTs !== expectedCurrentTimestamp
|
||||
) {
|
||||
throw new Error('doc_revision_conflict');
|
||||
}
|
||||
pushed.push({ docId, updates, editor: editorId });
|
||||
const prev = initialDocs.get(docId);
|
||||
const next = prev
|
||||
? mergeUpdates([Buffer.from(prev), ...updates.map(Buffer.from)])
|
||||
: updates.length === 1
|
||||
? Buffer.from(updates[0])
|
||||
: mergeUpdates(updates.map(Buffer.from));
|
||||
initialDocs.set(docId, next);
|
||||
if (editorId) {
|
||||
if (!prev && !creators.has(docId)) {
|
||||
creators.set(docId, editorId);
|
||||
}
|
||||
editors.set(docId, editorId);
|
||||
}
|
||||
clock += 1;
|
||||
timestamps.set(docId, clock);
|
||||
return { timestamp: clock, created: !prev };
|
||||
},
|
||||
async pushDocUpdatesTrusted(
|
||||
workspaceId: string,
|
||||
docId: string,
|
||||
updates: Uint8Array[],
|
||||
editorId?: string,
|
||||
expectedCurrentTimestamp?: number
|
||||
) {
|
||||
const { timestamp } = await this.pushDocUpdates(
|
||||
workspaceId,
|
||||
docId,
|
||||
updates,
|
||||
editorId,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
expectedCurrentTimestamp
|
||||
);
|
||||
return timestamp;
|
||||
},
|
||||
};
|
||||
|
||||
const event = {
|
||||
emit(_name: string, payload: { docId: string; updates: Uint8Array[] }) {
|
||||
emitted.push({ docId: payload.docId, updates: payload.updates });
|
||||
},
|
||||
};
|
||||
|
||||
const runtime = {
|
||||
async getWorkspaceLifecycleActiveV1() {
|
||||
return false;
|
||||
},
|
||||
};
|
||||
|
||||
const createWriter = () =>
|
||||
new DocWriter(storage as any, event as any, runtime as any);
|
||||
const writer = createWriter();
|
||||
return { writer, createWriter, storage, pushed, emitted, initialDocs };
|
||||
}
|
||||
|
||||
test('createDoc migrates legacy Any::Array root doc and registers new doc', async t => {
|
||||
const workspaceId = 'ws-legacy-migrate';
|
||||
const docs = new Map<string, Uint8Array>([
|
||||
[
|
||||
workspaceId,
|
||||
createLegacyArrayRootDoc([{ id: 'existing-doc', title: 'Existing' }]),
|
||||
],
|
||||
]);
|
||||
const { writer, pushed, initialDocs } = createWriterHarness(docs);
|
||||
|
||||
const { docId } = await writer.createDoc(
|
||||
workspaceId,
|
||||
'Fresh Title',
|
||||
'# Fresh Title\n\nBody',
|
||||
'user-1'
|
||||
);
|
||||
|
||||
t.truthy(docId);
|
||||
const rootPushes = pushed.filter(p => p.docId === workspaceId);
|
||||
t.is(
|
||||
rootPushes.length,
|
||||
1,
|
||||
'should push migration update and addDoc update in one atomic batch'
|
||||
);
|
||||
t.is(rootPushes[0].updates.length, 2);
|
||||
|
||||
const finalRoot = initialDocs.get(workspaceId)!;
|
||||
const pages = extractWorkspaceLifecycleRootPages(Buffer.from(finalRoot));
|
||||
t.deepEqual(
|
||||
pages.map(p => p.docId),
|
||||
['existing-doc', docId]
|
||||
);
|
||||
});
|
||||
|
||||
test('concurrent DocWriter instances coordinate legacy root migration via CAS even with interleaved root write', async t => {
|
||||
const workspaceId = 'ws-concurrent-cas';
|
||||
const docs = new Map<string, Uint8Array>([
|
||||
[
|
||||
workspaceId,
|
||||
createLegacyArrayRootDoc([{ id: 'existing-doc', title: 'Existing' }]),
|
||||
],
|
||||
]);
|
||||
|
||||
let interleavedInjected = false;
|
||||
let rootPushAttempts = 0;
|
||||
let harness!: ReturnType<typeof createWriterHarness>;
|
||||
harness = createWriterHarness(docs, {
|
||||
async onBeforePush({ docId }) {
|
||||
if (docId !== workspaceId) return;
|
||||
rootPushAttempts += 1;
|
||||
if (!interleavedInjected && rootPushAttempts === 1) {
|
||||
interleavedInjected = true;
|
||||
// Inject an unrelated normal root doc write between read and commit to force CAS retry.
|
||||
const extra = new YDoc();
|
||||
extra.getMap('meta').set('name', 'Interleaved Workspace Name');
|
||||
await harness.storage.pushDocUpdates(
|
||||
workspaceId,
|
||||
workspaceId,
|
||||
[Buffer.from(encodeStateAsUpdate(extra))],
|
||||
'interleaver'
|
||||
);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const writerA = harness.createWriter();
|
||||
const writerB = harness.createWriter();
|
||||
|
||||
const [resA, resB] = await Promise.all([
|
||||
writerA.createDoc(workspaceId, 'Doc A', '# Doc A', 'user-a'),
|
||||
writerB.createDoc(workspaceId, 'Doc B', '# Doc B', 'user-b'),
|
||||
]);
|
||||
|
||||
const finalRoot = harness.initialDocs.get(workspaceId)!;
|
||||
const pages = extractWorkspaceLifecycleRootPages(Buffer.from(finalRoot));
|
||||
const pageIds = pages.map(p => p.docId);
|
||||
t.is(pageIds.length, 3);
|
||||
t.is(new Set(pageIds).size, 3, 'no duplicate page ids');
|
||||
t.true(pageIds.includes('existing-doc'));
|
||||
t.true(pageIds.includes(resA.docId));
|
||||
t.true(pageIds.includes(resB.docId));
|
||||
|
||||
// Verify the migration batch only committed once across both instances.
|
||||
const migrationBatches = harness.pushed.filter(
|
||||
p => p.docId === workspaceId && p.updates.length === 2
|
||||
);
|
||||
t.is(migrationBatches.length, 1);
|
||||
});
|
||||
|
||||
test('createDoc rejects on root push DB error and registerDocInRootDoc recovers idempotently', async t => {
|
||||
const workspaceId = 'ws-root-db-error';
|
||||
const docs = new Map<string, Uint8Array>([
|
||||
[
|
||||
workspaceId,
|
||||
createLegacyArrayRootDoc([{ id: 'existing-doc', title: 'Existing' }]),
|
||||
],
|
||||
]);
|
||||
|
||||
let failRootPush = true;
|
||||
const { writer, initialDocs } = createWriterHarness(docs, {
|
||||
async onBeforePush({ docId }) {
|
||||
if (docId === workspaceId && failRootPush) {
|
||||
throw new Error('pg_connection_lost');
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const err = await t.throwsAsync(
|
||||
() => writer.createDoc(workspaceId, 'Recoverable Doc', '# Body', 'user-1'),
|
||||
{ instanceOf: DocCreateIncompleteError, message: /pg_connection_lost/ }
|
||||
);
|
||||
const createdDocId = err?.docId;
|
||||
t.truthy(createdDocId);
|
||||
|
||||
failRootPush = false;
|
||||
await writer.registerDocInRootDoc(
|
||||
workspaceId,
|
||||
createdDocId!,
|
||||
'Recoverable Doc',
|
||||
'user-1'
|
||||
);
|
||||
// Second call for the same docId is idempotent.
|
||||
await writer.registerDocInRootDoc(
|
||||
workspaceId,
|
||||
createdDocId!,
|
||||
'Recoverable Doc',
|
||||
'user-1'
|
||||
);
|
||||
|
||||
const pages = extractWorkspaceLifecycleRootPages(
|
||||
Buffer.from(initialDocs.get(workspaceId)!)
|
||||
);
|
||||
t.deepEqual(
|
||||
pages.map(p => p.docId),
|
||||
['existing-doc', createdDocId!]
|
||||
);
|
||||
});
|
||||
|
||||
function createPermissionMock(options?: { denyDocUpdateUsers?: Set<string> }) {
|
||||
const denied = options?.denyDocUpdateUsers ?? new Set<string>();
|
||||
return {
|
||||
user(userId: string) {
|
||||
return {
|
||||
workspace(_workspaceId: string) {
|
||||
return {
|
||||
async assert(_action: string) {},
|
||||
doc(_docId: string) {
|
||||
return {
|
||||
async assert(action: string) {
|
||||
if (action === 'Doc.Update' && denied.has(userId)) {
|
||||
throw new Error('Doc.Update access denied');
|
||||
}
|
||||
},
|
||||
async can(action: string) {
|
||||
return !(action === 'Doc.Update' && denied.has(userId));
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function readDocProperties(
|
||||
docs: Map<string, Uint8Array>,
|
||||
workspaceId: string,
|
||||
docId: string
|
||||
): { createdBy?: string; updatedBy?: string } {
|
||||
const bin = docs.get(`db$${workspaceId}$docProperties`);
|
||||
if (!bin) return {};
|
||||
const ydoc = new YDoc();
|
||||
applyUpdate(ydoc, bin);
|
||||
const entry = ydoc.getMap(docId);
|
||||
return {
|
||||
createdBy: entry.get('createdBy') as string | undefined,
|
||||
updatedBy: entry.get('updatedBy') as string | undefined,
|
||||
};
|
||||
}
|
||||
|
||||
test('MCP create_document recovers incomplete registration as collaborator without overwriting creator/updater or creating missing docs', async t => {
|
||||
const workspaceId = 'ws-mcp-recover';
|
||||
const propertiesDocId = `db$${workspaceId}$docProperties`;
|
||||
const docs = new Map<string, Uint8Array>([
|
||||
[
|
||||
workspaceId,
|
||||
createLegacyArrayRootDoc([{ id: 'existing-doc', title: 'Existing' }]),
|
||||
],
|
||||
]);
|
||||
|
||||
// Breakpoint 1: fail updateDocProperties right after body push succeeds.
|
||||
let failPropertiesPush = true;
|
||||
const { writer, storage, pushed, initialDocs } = createWriterHarness(docs, {
|
||||
async onBeforePush({ docId }) {
|
||||
if (docId === propertiesDocId && failPropertiesPush) {
|
||||
throw new Error('pg_connection_lost');
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const reader = {
|
||||
getDoc: (wsId: string, docId: string) => storage.getDoc(wsId, docId),
|
||||
};
|
||||
const ac = createPermissionMock({
|
||||
denyDocUpdateUsers: new Set(['unauthorized-user']),
|
||||
});
|
||||
const provider = new WorkspaceMcpProvider(
|
||||
ac as any,
|
||||
reader as any,
|
||||
writer,
|
||||
{} as any
|
||||
);
|
||||
|
||||
const prevEnv = (globalThis as any).env;
|
||||
(globalThis as any).env = {
|
||||
...prevEnv,
|
||||
dev: true,
|
||||
namespaces: { ...prevEnv?.namespaces, canary: true },
|
||||
};
|
||||
|
||||
try {
|
||||
const authorServer = await provider.for(
|
||||
'user-1',
|
||||
workspaceId,
|
||||
McpAccessMode.READ_WRITE
|
||||
);
|
||||
const authorCreateTool = authorServer.tools.find(
|
||||
tool => tool.name === 'create_document'
|
||||
)!;
|
||||
|
||||
// 1. Author's initial call fails during properties write; parse docId strictly from error payload.
|
||||
const first = await authorCreateTool.execute(
|
||||
{ title: 'MCP Recoverable', content: '# MCP Recoverable\n\nBody text' },
|
||||
{ signal: new AbortController().signal }
|
||||
);
|
||||
t.true(first.isError);
|
||||
const errorPayload = JSON.parse(first.content[0].text) as {
|
||||
success: boolean;
|
||||
code: string;
|
||||
retryable: boolean;
|
||||
docId: string;
|
||||
message: string;
|
||||
};
|
||||
t.false(errorPayload.success);
|
||||
t.is(errorPayload.code, 'doc_create_incomplete');
|
||||
t.true(errorPayload.retryable);
|
||||
const recoveredDocId = errorPayload.docId;
|
||||
t.truthy(recoveredDocId);
|
||||
|
||||
// 2. Restore DB and let a DIFFERENT authorized collaborator recover (and replay twice).
|
||||
failPropertiesPush = false;
|
||||
const collabServer = await provider.for(
|
||||
'collaborator-2',
|
||||
workspaceId,
|
||||
McpAccessMode.READ_WRITE
|
||||
);
|
||||
const collabCreateTool = collabServer.tools.find(
|
||||
tool => tool.name === 'create_document'
|
||||
)!;
|
||||
|
||||
for (let replay = 0; replay < 2; replay++) {
|
||||
const res = await collabCreateTool.execute(
|
||||
{
|
||||
title: 'Collaborator Fallback Title',
|
||||
content: 'Ignored content',
|
||||
docId: recoveredDocId,
|
||||
},
|
||||
{ signal: new AbortController().signal }
|
||||
);
|
||||
t.falsy(res.isError);
|
||||
const payload = JSON.parse(res.content[0].text) as {
|
||||
success: boolean;
|
||||
docId: string;
|
||||
};
|
||||
t.true(payload.success);
|
||||
t.is(payload.docId, recoveredDocId);
|
||||
}
|
||||
|
||||
// Body pushed only once; creator/updater preserved as original author 'user-1'.
|
||||
t.is(pushed.filter(p => p.docId === recoveredDocId).length, 1);
|
||||
t.deepEqual(readDocProperties(initialDocs, workspaceId, recoveredDocId), {
|
||||
createdBy: 'user-1',
|
||||
updatedBy: 'user-1',
|
||||
});
|
||||
|
||||
const pages = extractWorkspaceLifecycleRootPages(
|
||||
Buffer.from(initialDocs.get(workspaceId)!)
|
||||
);
|
||||
t.deepEqual(
|
||||
pages.map(p => p.docId),
|
||||
['existing-doc', recoveredDocId]
|
||||
);
|
||||
|
||||
// 3. After a third editor updates the doc, collaborator calling create_document with docId
|
||||
// must leave createdBy/updatedBy and body completely untouched.
|
||||
await writer.updateDocMeta(
|
||||
workspaceId,
|
||||
recoveredDocId,
|
||||
{ title: 'Updated Title by editor-3' },
|
||||
'editor-3'
|
||||
);
|
||||
const pushCountBeforeNoop = pushed.length;
|
||||
const noopRes = await collabCreateTool.execute(
|
||||
{
|
||||
title: 'Should Not Overwrite',
|
||||
content: 'Should Not Overwrite',
|
||||
docId: recoveredDocId,
|
||||
},
|
||||
{ signal: new AbortController().signal }
|
||||
);
|
||||
t.falsy(noopRes.isError);
|
||||
t.is(
|
||||
pushed.length,
|
||||
pushCountBeforeNoop,
|
||||
'no storage writes on already-complete doc'
|
||||
);
|
||||
t.deepEqual(readDocProperties(initialDocs, workspaceId, recoveredDocId), {
|
||||
createdBy: 'user-1',
|
||||
updatedBy: 'editor-3',
|
||||
});
|
||||
|
||||
// 4. Negative cases: nonexistent docId fails with not found without creating any doc.
|
||||
const missingRes = await collabCreateTool.execute(
|
||||
{ title: 'Ghost', content: 'Body', docId: 'nonexistent-doc-id' },
|
||||
{ signal: new AbortController().signal }
|
||||
);
|
||||
t.true(missingRes.isError);
|
||||
t.regex(missingRes.content[0].text, /not found/i);
|
||||
t.false(initialDocs.has('nonexistent-doc-id'));
|
||||
|
||||
// Reserved IDs rejected.
|
||||
const reservedRes = await authorCreateTool.execute(
|
||||
{ title: 'Bad', content: 'Body', docId: workspaceId },
|
||||
{ signal: new AbortController().signal }
|
||||
);
|
||||
t.true(reservedRes.isError);
|
||||
t.regex(reservedRes.content[0].text, /Invalid document ID/);
|
||||
|
||||
const dbReservedRes = await authorCreateTool.execute(
|
||||
{ title: 'Bad', content: 'Body', docId: propertiesDocId },
|
||||
{ signal: new AbortController().signal }
|
||||
);
|
||||
t.true(dbReservedRes.isError);
|
||||
t.regex(dbReservedRes.content[0].text, /Invalid document ID/);
|
||||
|
||||
// Unauthorized user without Doc.Update rejected.
|
||||
const unauthServer = await provider.for(
|
||||
'unauthorized-user',
|
||||
workspaceId,
|
||||
McpAccessMode.READ_WRITE
|
||||
);
|
||||
const unauthCreateTool = unauthServer.tools.find(
|
||||
tool => tool.name === 'create_document'
|
||||
)!;
|
||||
const deniedRes = await unauthCreateTool.execute(
|
||||
{ title: 'Hijack', content: 'Body', docId: recoveredDocId },
|
||||
{ signal: new AbortController().signal }
|
||||
);
|
||||
t.true(deniedRes.isError);
|
||||
t.regex(deniedRes.content[0].text, /Doc\.Update access denied/);
|
||||
} finally {
|
||||
(globalThis as any).env = prevEnv;
|
||||
}
|
||||
});
|
||||
|
||||
test('Copilot doc_create via executeToolCall recovers from error message hint and rejects unknown retry keys', async t => {
|
||||
const workspaceId = 'ws-copilot-recover';
|
||||
const propertiesDocId = `db$${workspaceId}$docProperties`;
|
||||
const docs = new Map<string, Uint8Array>([
|
||||
[
|
||||
workspaceId,
|
||||
createLegacyArrayRootDoc([{ id: 'existing-doc', title: 'Existing' }]),
|
||||
],
|
||||
]);
|
||||
|
||||
// Breakpoint 2: properties succeed, root push fails.
|
||||
let failRootPush = true;
|
||||
const { writer, pushed, initialDocs } = createWriterHarness(docs, {
|
||||
async onBeforePush({ docId }) {
|
||||
if (docId === workspaceId && failRootPush) {
|
||||
throw new Error('pg_connection_lost');
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const ac = createPermissionMock({
|
||||
denyDocUpdateUsers: new Set(['unauthorized-user']),
|
||||
});
|
||||
const handler = buildDocCreateHandler(writer, ac as any);
|
||||
const authorTools = {
|
||||
doc_create: createDocCreateTool(
|
||||
handler.bind(null, { user: 'user-1', workspace: workspaceId } as any)
|
||||
),
|
||||
};
|
||||
const collabTools = {
|
||||
doc_create: createDocCreateTool(
|
||||
handler.bind(null, {
|
||||
user: 'collaborator-2',
|
||||
workspace: workspaceId,
|
||||
} as any)
|
||||
),
|
||||
};
|
||||
|
||||
const firstCall = await executeToolCall(
|
||||
authorTools,
|
||||
{
|
||||
callId: 'call-1',
|
||||
name: 'doc_create',
|
||||
args: {
|
||||
title: 'Copilot Recoverable',
|
||||
content: '# Copilot Recoverable\n\nBody',
|
||||
},
|
||||
},
|
||||
{} as any
|
||||
);
|
||||
const first = firstCall.output as {
|
||||
type?: string;
|
||||
code?: string;
|
||||
retryable?: boolean;
|
||||
message?: string;
|
||||
locator?: { doc_id?: string; docId?: string };
|
||||
};
|
||||
t.is(first.type, 'error');
|
||||
t.is(first.code, 'doc_create_incomplete');
|
||||
t.true(first.retryable);
|
||||
const retryMatch = /retry with (\w+)="([^"]+)"/.exec(first.message ?? '');
|
||||
t.truthy(
|
||||
retryMatch,
|
||||
'error message must include machine-parseable retry hint'
|
||||
);
|
||||
const [, retryKey, recoveredDocId] = retryMatch!;
|
||||
t.is(retryKey, 'doc_id');
|
||||
t.is(first.locator?.doc_id, recoveredDocId);
|
||||
t.is(first.locator?.docId, recoveredDocId);
|
||||
|
||||
const propsPushesBeforeRecovery = pushed.filter(
|
||||
p => p.docId === propertiesDocId
|
||||
).length;
|
||||
t.is(propsPushesBeforeRecovery, 1);
|
||||
|
||||
failRootPush = false;
|
||||
for (let replay = 0; replay < 2; replay++) {
|
||||
const retryCall = await executeToolCall(
|
||||
collabTools,
|
||||
{
|
||||
callId: `call-retry-${replay}`,
|
||||
name: 'doc_create',
|
||||
args: {
|
||||
title: 'Collaborator Fallback',
|
||||
content: 'Ignored',
|
||||
[retryKey]: recoveredDocId,
|
||||
},
|
||||
},
|
||||
{} as any
|
||||
);
|
||||
t.falsy(retryCall.isError);
|
||||
const res = retryCall.output as {
|
||||
success?: boolean;
|
||||
docId?: string;
|
||||
message?: string;
|
||||
};
|
||||
t.true(res.success);
|
||||
t.is(res.docId, recoveredDocId);
|
||||
t.regex(res.message ?? '', /registration completed/);
|
||||
}
|
||||
|
||||
// Body pushed once; properties NOT rewritten when already populated; root has 1 entry.
|
||||
t.is(pushed.filter(p => p.docId === recoveredDocId).length, 1);
|
||||
t.is(
|
||||
pushed.filter(p => p.docId === propertiesDocId).length,
|
||||
propsPushesBeforeRecovery,
|
||||
'must not rewrite db$docProperties when createdBy and updatedBy already exist'
|
||||
);
|
||||
t.deepEqual(readDocProperties(initialDocs, workspaceId, recoveredDocId), {
|
||||
createdBy: 'user-1',
|
||||
updatedBy: 'user-1',
|
||||
});
|
||||
const pages = extractWorkspaceLifecycleRootPages(
|
||||
Buffer.from(initialDocs.get(workspaceId)!)
|
||||
);
|
||||
t.deepEqual(
|
||||
pages.map(p => p.docId),
|
||||
['existing-doc', recoveredDocId]
|
||||
);
|
||||
|
||||
// Unknown retry field (e.g. documentId) must be rejected by .strict() without creating a second doc!
|
||||
const unknownKeyCall = await executeToolCall(
|
||||
collabTools,
|
||||
{
|
||||
callId: 'call-unknown-key',
|
||||
name: 'doc_create',
|
||||
args: {
|
||||
title: 'Duplicate Risk',
|
||||
content: 'Body',
|
||||
documentId: recoveredDocId,
|
||||
},
|
||||
},
|
||||
{} as any
|
||||
);
|
||||
t.true(unknownKeyCall.isError);
|
||||
t.deepEqual(
|
||||
[...initialDocs.keys()].filter(
|
||||
id => id !== workspaceId && !id.startsWith('db$')
|
||||
),
|
||||
[recoveredDocId]
|
||||
);
|
||||
|
||||
// Nonexistent doc_id rejected without creating any doc
|
||||
const missingCall = await executeToolCall(
|
||||
collabTools,
|
||||
{
|
||||
callId: 'call-missing',
|
||||
name: 'doc_create',
|
||||
args: { title: 'Ghost', content: 'Body', doc_id: 'does-not-exist' },
|
||||
},
|
||||
{} as any
|
||||
);
|
||||
const missing = missingCall.output as { type?: string; message?: string };
|
||||
t.is(missing.type, 'error');
|
||||
t.regex(missing.message ?? '', /not found/i);
|
||||
t.false(initialDocs.has('does-not-exist'));
|
||||
|
||||
// Reserved ID rejected
|
||||
const badIdCall = await executeToolCall(
|
||||
authorTools,
|
||||
{
|
||||
callId: 'call-bad-id',
|
||||
name: 'doc_create',
|
||||
args: { title: 'Bad', content: 'Body', doc_id: propertiesDocId },
|
||||
},
|
||||
{} as any
|
||||
);
|
||||
const badId = badIdCall.output as { type?: string; message?: string };
|
||||
t.is(badId.type, 'error');
|
||||
t.regex(badId.message ?? '', /Invalid document ID/);
|
||||
|
||||
// Existing doc_id without Doc.Update permission rejected
|
||||
const unauthTools = {
|
||||
doc_create: createDocCreateTool(
|
||||
handler.bind(null, {
|
||||
user: 'unauthorized-user',
|
||||
workspace: workspaceId,
|
||||
} as any)
|
||||
),
|
||||
};
|
||||
const deniedCall = await executeToolCall(
|
||||
unauthTools,
|
||||
{
|
||||
callId: 'call-denied',
|
||||
name: 'doc_create',
|
||||
args: { title: 'Hijack', content: 'Body', doc_id: recoveredDocId },
|
||||
},
|
||||
{} as any
|
||||
);
|
||||
const denied = deniedCall.output as { type?: string; message?: string };
|
||||
t.is(denied.type, 'error');
|
||||
t.regex(denied.message ?? '', /Doc\.Update access denied/);
|
||||
});
|
||||
|
||||
test('recoverDocCreation uses CAS on db$docProperties so interleaved updatedBy is never overwritten', async t => {
|
||||
const workspaceId = 'ws-props-cas';
|
||||
const propertiesDocId = `db$${workspaceId}$docProperties`;
|
||||
const docs = new Map<string, Uint8Array>([
|
||||
[
|
||||
workspaceId,
|
||||
createLegacyArrayRootDoc([{ id: 'existing-doc', title: 'Existing' }]),
|
||||
],
|
||||
]);
|
||||
|
||||
let failFirstProps = true;
|
||||
let interleavedInjected = false;
|
||||
let recoveryDocId = '';
|
||||
let harness!: ReturnType<typeof createWriterHarness>;
|
||||
harness = createWriterHarness(docs, {
|
||||
async onBeforePush({ docId, expectedCurrentTimestamp }) {
|
||||
if (docId !== propertiesDocId) return;
|
||||
if (failFirstProps) {
|
||||
failFirstProps = false;
|
||||
throw new Error('pg_connection_lost');
|
||||
}
|
||||
if (!interleavedInjected && expectedCurrentTimestamp !== undefined) {
|
||||
interleavedInjected = true;
|
||||
const interleavedUpdate = updateDocProperties(
|
||||
Buffer.alloc(0),
|
||||
propertiesDocId,
|
||||
recoveryDocId,
|
||||
undefined,
|
||||
'interleaved-editor-3'
|
||||
);
|
||||
await harness.storage.pushDocUpdatesTrusted(
|
||||
workspaceId,
|
||||
propertiesDocId,
|
||||
[interleavedUpdate],
|
||||
'interleaved-editor-3'
|
||||
);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const err = await t.throwsAsync(
|
||||
() =>
|
||||
harness.writer.createDoc(
|
||||
workspaceId,
|
||||
'CAS Props Doc',
|
||||
'# Body',
|
||||
'user-1'
|
||||
),
|
||||
{ instanceOf: DocCreateIncompleteError }
|
||||
);
|
||||
recoveryDocId = err!.docId;
|
||||
|
||||
await harness.writer.recoverDocCreation(
|
||||
workspaceId,
|
||||
recoveryDocId,
|
||||
'Fallback',
|
||||
'collaborator-2'
|
||||
);
|
||||
|
||||
t.true(interleavedInjected);
|
||||
t.deepEqual(readDocProperties(docs, workspaceId, recoveryDocId), {
|
||||
createdBy: 'user-1',
|
||||
updatedBy: 'interleaved-editor-3',
|
||||
});
|
||||
});
|
||||
|
||||
test('recoverDocCreation leaves createdBy unset for legacy doc without traceable creator record', async t => {
|
||||
const workspaceId = 'ws-legacy-no-creator';
|
||||
const legacyDocId = 'legacy-doc-1';
|
||||
const legacyDocBin = createDocWithMarkdown(
|
||||
'Legacy Doc',
|
||||
'Edited body',
|
||||
legacyDocId,
|
||||
{
|
||||
actorUserId: 'later-editor',
|
||||
timestampMs: 1000,
|
||||
}
|
||||
);
|
||||
const docs = new Map<string, Uint8Array>([
|
||||
[workspaceId, createLegacyArrayRootDoc([])],
|
||||
[legacyDocId, legacyDocBin],
|
||||
]);
|
||||
|
||||
// Simulate legacy doc with no traceable creator record (creator=undefined) and editor='later-editor'.
|
||||
const { writer } = createWriterHarness(docs, {
|
||||
initialEditors: new Map([[legacyDocId, 'later-editor']]),
|
||||
});
|
||||
|
||||
await writer.recoverDocCreation(
|
||||
workspaceId,
|
||||
legacyDocId,
|
||||
'Fallback',
|
||||
'collaborator-2'
|
||||
);
|
||||
|
||||
t.deepEqual(readDocProperties(docs, workspaceId, legacyDocId), {
|
||||
createdBy: undefined,
|
||||
updatedBy: 'later-editor',
|
||||
});
|
||||
});
|
||||
|
||||
test('createDoc warns and does not fail when root doc cannot be migrated', async t => {
|
||||
const workspaceId = 'ws-corrupt-root';
|
||||
const corruptRoot = new YDoc();
|
||||
corruptRoot.getMap('meta').set('pages', 'not-an-array');
|
||||
const docs = new Map<string, Uint8Array>([
|
||||
[workspaceId, Buffer.from(encodeStateAsUpdate(corruptRoot))],
|
||||
]);
|
||||
const { writer, initialDocs } = createWriterHarness(docs);
|
||||
|
||||
const { docId } = await writer.createDoc(
|
||||
workspaceId,
|
||||
'Safe Doc',
|
||||
'hello',
|
||||
'user-1'
|
||||
);
|
||||
|
||||
t.truthy(docId);
|
||||
t.truthy(initialDocs.get(docId));
|
||||
});
|
||||
|
||||
test('updateDocMeta skips empty title update and updates root doc via native helper', async t => {
|
||||
const workspaceId = 'ws-meta-title';
|
||||
const docId = 'doc-1';
|
||||
const initialDoc = createDocWithMarkdown('Old Title', 'body', docId);
|
||||
const rootDoc = new YDoc();
|
||||
const pages = new YArray<YMap<unknown>>();
|
||||
const pageMap = new YMap<unknown>();
|
||||
pageMap.set('id', docId);
|
||||
pageMap.set('title', 'Old Title');
|
||||
pages.push([pageMap]);
|
||||
rootDoc.getMap('meta').set('pages', pages);
|
||||
const rootBin = Buffer.from(encodeStateAsUpdate(rootDoc));
|
||||
|
||||
const docs = new Map<string, Uint8Array>([
|
||||
[docId, initialDoc],
|
||||
[workspaceId, rootBin],
|
||||
]);
|
||||
const { writer, pushed, initialDocs } = createWriterHarness(docs);
|
||||
|
||||
// Unchanged title should not push doc update or root update
|
||||
await writer.updateDocMeta(workspaceId, docId, { title: 'Old Title' }, 'u1');
|
||||
t.false(pushed.some(p => p.docId === docId));
|
||||
t.false(pushed.some(p => p.docId === workspaceId));
|
||||
|
||||
// Changed title should push both doc and root updates
|
||||
await writer.updateDocMeta(workspaceId, docId, { title: 'New Title' }, 'u1');
|
||||
t.true(pushed.some(p => p.docId === docId));
|
||||
t.true(pushed.some(p => p.docId === workspaceId));
|
||||
|
||||
const updatedRoot = new YDoc();
|
||||
applyUpdate(updatedRoot, initialDocs.get(workspaceId)!);
|
||||
const updatedPages = updatedRoot.getMap('meta').toJSON().pages as Array<{
|
||||
id: string;
|
||||
title: string;
|
||||
}>;
|
||||
t.is(updatedPages[0].title, 'New Title');
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import test from 'ava';
|
||||
import { Doc as YDoc } from 'yjs';
|
||||
|
||||
import { SpaceSyncGateway } from '../../core/sync/gateway';
|
||||
|
||||
test('onClusterDocUpdatesPushed skips re-merging when compressed flag is present', t => {
|
||||
const doc = new YDoc();
|
||||
const rawUpdates: Uint8Array[] = [];
|
||||
doc.on('update', (u: Uint8Array) => rawUpdates.push(u));
|
||||
doc.getText('content').insert(0, 'hello');
|
||||
doc.getText('content').insert(5, ' world');
|
||||
t.is(rawUpdates.length, 2);
|
||||
|
||||
const emitted: Array<{ event: string; payload: any }> = [];
|
||||
const fakeSocket = {
|
||||
id: 'sock-1',
|
||||
emit(event: string, payload: any) {
|
||||
emitted.push({ event, payload });
|
||||
},
|
||||
};
|
||||
|
||||
// Instantiate SpaceSyncGateway prototype without NestJS DI to test cluster handler in isolation
|
||||
const gateway = Object.create(SpaceSyncGateway.prototype) as any;
|
||||
gateway.activeDocSockets = new Map([
|
||||
['workspace:ws-1:doc-1', new Set([fakeSocket])],
|
||||
]);
|
||||
let buildBroadcastCalls = 0;
|
||||
gateway.buildBroadcastPayload = () => {
|
||||
buildBroadcastCalls += 1;
|
||||
throw new Error('should not re-merge pre-compressed cluster broadcast');
|
||||
};
|
||||
|
||||
const preCompressedBase64 = Buffer.from(rawUpdates[0]).toString('base64');
|
||||
gateway.onClusterDocUpdatesPushed({
|
||||
spaceType: 'workspace',
|
||||
spaceId: 'ws-1',
|
||||
docId: 'doc-1',
|
||||
updates: [preCompressedBase64],
|
||||
timestamp: 123456,
|
||||
editor: 'editor-1',
|
||||
compressed: true,
|
||||
});
|
||||
|
||||
t.is(buildBroadcastCalls, 0);
|
||||
t.is(emitted.length, 1);
|
||||
t.is(emitted[0].event, 'space:broadcast-doc-updates');
|
||||
t.deepEqual(emitted[0].payload, {
|
||||
spaceType: 'workspace',
|
||||
spaceId: 'ws-1',
|
||||
docId: 'doc-1',
|
||||
updates: [preCompressedBase64],
|
||||
timestamp: 123456,
|
||||
editor: 'editor-1',
|
||||
compressed: true,
|
||||
});
|
||||
});
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
import test from 'ava';
|
||||
import { Doc as YDoc, encodeStateAsUpdate } from 'yjs';
|
||||
|
||||
import { WorkspaceLifecycleMigration } from '../workspace-lifecycle';
|
||||
|
||||
test('migrate handles 200,000 root pages without stack overflow and preserves rootStatus', async t => {
|
||||
const count = 200_000;
|
||||
const doc = new YDoc();
|
||||
const pages = Array.from({ length: count }, (_, i) => ({
|
||||
id: `doc-${i}`,
|
||||
trash: i % 10 === 0,
|
||||
}));
|
||||
doc.getMap('meta').set('pages', pages);
|
||||
const rootBin = Buffer.from(encodeStateAsUpdate(doc));
|
||||
|
||||
let migratedInput:
|
||||
| {
|
||||
workspaceId: string;
|
||||
sourceRevision: string;
|
||||
rootStatus: string;
|
||||
docs: { docId: string; trashed: boolean }[];
|
||||
}
|
||||
| undefined;
|
||||
|
||||
const migration = new WorkspaceLifecycleMigration({
|
||||
async listWorkspaceLifecycleMigrationCandidatesV1() {
|
||||
return [];
|
||||
},
|
||||
async prepareWorkspaceLifecycleMigrationV1() {
|
||||
return {
|
||||
completed: false,
|
||||
revision: 'rev-200k',
|
||||
rootStatus: 'present',
|
||||
bin: rootBin,
|
||||
} as any;
|
||||
},
|
||||
async migrateWorkspaceLifecycleV1(input) {
|
||||
migratedInput = input as any;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
await migration.ensure('ws-200k');
|
||||
|
||||
t.truthy(migratedInput);
|
||||
t.is(migratedInput!.rootStatus, 'present');
|
||||
t.is(migratedInput!.docs.length, count);
|
||||
t.deepEqual(migratedInput!.docs[0], { docId: 'doc-0', trashed: true });
|
||||
t.deepEqual(migratedInput!.docs[1], { docId: 'doc-1', trashed: false });
|
||||
t.deepEqual(migratedInput!.docs[count - 1], {
|
||||
docId: `doc-${count - 1}`,
|
||||
trashed: false,
|
||||
});
|
||||
});
|
||||
|
||||
test('migrate propagates resource limit errors without marking completed and succeeds on retry with default budget', async t => {
|
||||
const doc = new YDoc();
|
||||
doc.getMap('meta').set('name', 'Budget Test Workspace');
|
||||
doc.getMap('meta').set('pages', [
|
||||
{ id: 'doc-trashed', trash: true },
|
||||
{ id: 'doc-active', trash: false },
|
||||
]);
|
||||
const rootBin = Buffer.from(encodeStateAsUpdate(doc));
|
||||
|
||||
let migrateCalls = 0;
|
||||
let migratedInput:
|
||||
| {
|
||||
workspaceId: string;
|
||||
sourceRevision: string;
|
||||
rootStatus: string;
|
||||
docs: { docId: string; trashed: boolean }[];
|
||||
}
|
||||
| undefined;
|
||||
|
||||
const runtime = {
|
||||
async listWorkspaceLifecycleMigrationCandidatesV1() {
|
||||
return [];
|
||||
},
|
||||
async prepareWorkspaceLifecycleMigrationV1() {
|
||||
return {
|
||||
completed: false,
|
||||
revision: 'rev-budget',
|
||||
rootStatus: 'present',
|
||||
bin: rootBin,
|
||||
} as any;
|
||||
},
|
||||
async migrateWorkspaceLifecycleV1(input: any) {
|
||||
migrateCalls += 1;
|
||||
migratedInput = input;
|
||||
return true;
|
||||
},
|
||||
};
|
||||
|
||||
const constrained = new WorkspaceLifecycleMigration(runtime, {
|
||||
maxStructs: 1,
|
||||
});
|
||||
await t.throwsAsync(() => constrained.ensure('ws-budget'), {
|
||||
message: /\[affine-doc:resource_limit\]/,
|
||||
});
|
||||
t.is(
|
||||
migrateCalls,
|
||||
0,
|
||||
'must not commit completed checkpoint when resource limit is exceeded'
|
||||
);
|
||||
|
||||
const defaultBudget = new WorkspaceLifecycleMigration(runtime);
|
||||
await defaultBudget.ensure('ws-budget');
|
||||
t.is(migrateCalls, 1);
|
||||
t.truthy(migratedInput);
|
||||
t.is(migratedInput!.sourceRevision, 'rev-budget');
|
||||
t.is(migratedInput!.rootStatus, 'present');
|
||||
t.deepEqual(migratedInput!.docs, [
|
||||
{ docId: 'doc-trashed', trashed: true },
|
||||
{ docId: 'doc-active', trashed: false },
|
||||
]);
|
||||
});
|
||||
|
||||
test('migrate still degrades corrupt binary to invalid_metadata with empty docs', async t => {
|
||||
let migratedInput:
|
||||
| {
|
||||
workspaceId: string;
|
||||
sourceRevision: string;
|
||||
rootStatus: string;
|
||||
docs: { docId: string; trashed: boolean }[];
|
||||
}
|
||||
| undefined;
|
||||
|
||||
const migration = new WorkspaceLifecycleMigration({
|
||||
async listWorkspaceLifecycleMigrationCandidatesV1() {
|
||||
return [];
|
||||
},
|
||||
async prepareWorkspaceLifecycleMigrationV1() {
|
||||
return {
|
||||
completed: false,
|
||||
revision: 'rev-corrupt',
|
||||
rootStatus: 'present',
|
||||
bin: Buffer.from([255]),
|
||||
} as any;
|
||||
},
|
||||
async migrateWorkspaceLifecycleV1(input) {
|
||||
migratedInput = input as any;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
await migration.ensure('ws-corrupt');
|
||||
t.truthy(migratedInput);
|
||||
t.is(migratedInput!.rootStatus, 'invalid_metadata');
|
||||
t.deepEqual(migratedInput!.docs, []);
|
||||
});
|
||||
@@ -294,6 +294,7 @@ export class BackendRuntimeCoreOperations {
|
||||
|
||||
expectedPermissionGeneration?: number;
|
||||
protocolVersion?: number;
|
||||
expectedCurrentTimestamp?: number;
|
||||
}): Promise<{ timestamp: number; created: boolean }> {
|
||||
return await this.measured(
|
||||
'appendWorkspaceDocUpdatesV1',
|
||||
@@ -307,6 +308,7 @@ export class BackendRuntimeCoreOperations {
|
||||
docId: string;
|
||||
updates: Buffer[];
|
||||
editorId?: string;
|
||||
expectedCurrentTimestamp?: number;
|
||||
}): Promise<number> {
|
||||
return await this.measured('appendWorkspaceDocUpdatesTrustedV1', runtime =>
|
||||
runtime.appendWorkspaceDocUpdatesTrustedV1(input)
|
||||
@@ -321,6 +323,14 @@ export class BackendRuntimeCoreOperations {
|
||||
);
|
||||
}
|
||||
|
||||
getWorkspaceDocCreatorV1(workspaceId: string, docId: string) {
|
||||
return this.measured(
|
||||
'getWorkspaceDocCreatorV1',
|
||||
runtime => runtime.getWorkspaceDocCreatorV1(workspaceId, docId),
|
||||
{ workspaceId, docId }
|
||||
);
|
||||
}
|
||||
|
||||
async runWorkspaceLifecycleMigrationsV1() {
|
||||
await this.workspaceLifecycle.run();
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import * as Y from 'yjs';
|
||||
|
||||
import { extractWorkspaceLifecycleRootPages } from '../../native';
|
||||
import type { RuntimeInstance } from './contracts';
|
||||
|
||||
export class WorkspaceLifecycleMigration {
|
||||
@@ -15,7 +15,8 @@ export class WorkspaceLifecycleMigration {
|
||||
| 'listWorkspaceLifecycleMigrationCandidatesV1'
|
||||
| 'prepareWorkspaceLifecycleMigrationV1'
|
||||
| 'migrateWorkspaceLifecycleV1'
|
||||
>
|
||||
>,
|
||||
private readonly options?: { maxStructs?: number }
|
||||
) {}
|
||||
|
||||
start() {
|
||||
@@ -90,32 +91,28 @@ export class WorkspaceLifecycleMigration {
|
||||
return;
|
||||
}
|
||||
let rootStatus = source.rootStatus;
|
||||
const docs: { docId: string; trashed: boolean }[] = [];
|
||||
let docs: { docId: string; trashed: boolean }[] = [];
|
||||
if (source.bin) {
|
||||
const root = new Y.Doc();
|
||||
try {
|
||||
Y.applyUpdate(root, source.bin);
|
||||
const pages: unknown = root.getMap('meta').toJSON().pages;
|
||||
if (Array.isArray(pages)) {
|
||||
for (const page of pages) {
|
||||
if (typeof page !== 'object' || page === null || !('id' in page))
|
||||
continue;
|
||||
const docId: unknown = page.id;
|
||||
if (typeof docId !== 'string' || !docId.trim()) continue;
|
||||
docs.push({
|
||||
docId,
|
||||
trashed: 'trash' in page && page.trash === true,
|
||||
});
|
||||
}
|
||||
docs = extractWorkspaceLifecycleRootPages(
|
||||
Buffer.from(
|
||||
source.bin.buffer,
|
||||
source.bin.byteOffset,
|
||||
source.bin.byteLength
|
||||
),
|
||||
this.options?.maxStructs
|
||||
);
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof Error ? error.message : String(error);
|
||||
if (message.includes('[affine-doc:resource_limit]')) {
|
||||
throw error;
|
||||
}
|
||||
} catch {
|
||||
docs.length = 0;
|
||||
docs = [];
|
||||
rootStatus = 'invalid_metadata';
|
||||
this.logger.warn(
|
||||
`Ignoring invalid legacy root metadata during workspace lifecycle migration: ${workspaceId}`
|
||||
);
|
||||
} finally {
|
||||
root.destroy();
|
||||
}
|
||||
}
|
||||
const completed = await this.runtime.migrateWorkspaceLifecycleV1({
|
||||
|
||||
@@ -83,7 +83,8 @@ export class PgUserspaceDocStorageAdapter extends DocStorageAdapter {
|
||||
userId: string,
|
||||
docId: string,
|
||||
updates: Uint8Array[],
|
||||
editorId = userId
|
||||
editorId = userId,
|
||||
_expectedCurrentTimestamp?: number
|
||||
) {
|
||||
return (await this.pushDocUpdates(userId, docId, updates, editorId))
|
||||
.timestamp;
|
||||
|
||||
@@ -69,7 +69,8 @@ export class PgWorkspaceDocStorageAdapter extends DocStorageAdapter {
|
||||
editorId: string,
|
||||
expectedPermissionGeneration?: number,
|
||||
writeIntent: 'update_doc' | 'create_doc' = 'update_doc',
|
||||
protocolVersion?: number
|
||||
protocolVersion?: number,
|
||||
expectedCurrentTimestamp?: number
|
||||
) {
|
||||
return await this.pushDocUpdatesWithContract(
|
||||
workspaceId,
|
||||
@@ -81,6 +82,7 @@ export class PgWorkspaceDocStorageAdapter extends DocStorageAdapter {
|
||||
writeIntent,
|
||||
expectedPermissionGeneration,
|
||||
protocolVersion,
|
||||
expectedCurrentTimestamp,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -89,7 +91,8 @@ export class PgWorkspaceDocStorageAdapter extends DocStorageAdapter {
|
||||
workspaceId: string,
|
||||
docId: string,
|
||||
updates: Uint8Array[],
|
||||
editorId?: string
|
||||
editorId?: string,
|
||||
expectedCurrentTimestamp?: number
|
||||
) {
|
||||
return (
|
||||
await this.pushDocUpdatesWithContract(
|
||||
@@ -97,7 +100,7 @@ export class PgWorkspaceDocStorageAdapter extends DocStorageAdapter {
|
||||
docId,
|
||||
updates,
|
||||
editorId,
|
||||
{ trusted: true }
|
||||
{ trusted: true, expectedCurrentTimestamp }
|
||||
)
|
||||
).timestamp;
|
||||
}
|
||||
@@ -114,8 +117,9 @@ export class PgWorkspaceDocStorageAdapter extends DocStorageAdapter {
|
||||
|
||||
expectedPermissionGeneration?: number;
|
||||
protocolVersion?: number;
|
||||
expectedCurrentTimestamp?: number;
|
||||
}
|
||||
| { trusted: true }
|
||||
| { trusted: true; expectedCurrentTimestamp?: number }
|
||||
) {
|
||||
if (!updates.length) {
|
||||
return { timestamp: 0, created: false };
|
||||
@@ -132,6 +136,7 @@ export class PgWorkspaceDocStorageAdapter extends DocStorageAdapter {
|
||||
timestamp: await this.runtime.appendWorkspaceDocUpdatesTrustedV1({
|
||||
...input,
|
||||
editorId,
|
||||
expectedCurrentTimestamp: contract.expectedCurrentTimestamp,
|
||||
}),
|
||||
created: false,
|
||||
}
|
||||
@@ -301,14 +306,19 @@ export class PgWorkspaceDocStorageAdapter extends DocStorageAdapter {
|
||||
};
|
||||
}
|
||||
|
||||
protected async setDocSnapshot(snapshot: DocRecord) {
|
||||
protected async setDocSnapshot(
|
||||
snapshot: DocRecord,
|
||||
options?: { fromInitialUpdates?: boolean }
|
||||
) {
|
||||
try {
|
||||
return await this.runtime.upsertDocSnapshot(
|
||||
snapshot.spaceId,
|
||||
snapshot.docId,
|
||||
Buffer.from(snapshot.bin),
|
||||
snapshot.timestamp,
|
||||
snapshot.editor
|
||||
snapshot.editor,
|
||||
options?.fromInitialUpdates ? snapshot.creator : undefined,
|
||||
options?.fromInitialUpdates
|
||||
);
|
||||
} catch (e) {
|
||||
metrics.doc.counter('snapshot_upsert_failed').add(1);
|
||||
|
||||
@@ -6,18 +6,11 @@ declare global {
|
||||
history: {
|
||||
interval: number;
|
||||
};
|
||||
experimental: {
|
||||
yocto: boolean;
|
||||
};
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
defineModuleConfig('doc', {
|
||||
'experimental.yocto': {
|
||||
desc: 'Use `y-octo` to merge updates at the same time when merging using Yjs.',
|
||||
default: false,
|
||||
},
|
||||
'history.interval': {
|
||||
desc: 'The minimum time interval in milliseconds of creating a new history snapshot when doc get updated.',
|
||||
default: 1000 * 60 * 10 /* 10 mins */,
|
||||
|
||||
@@ -12,7 +12,7 @@ import { DocEventsListener } from './event';
|
||||
import { DocStorageCronJob } from './job';
|
||||
import { DocStorageOptions } from './options';
|
||||
import { DatabaseDocReader, DocReader, DocReaderProvider } from './reader';
|
||||
import { DocWriter } from './writer';
|
||||
import { DocCreateIncompleteError, DocWriter } from './writer';
|
||||
|
||||
@Module({
|
||||
imports: [BackendRuntimeModule, QuotaModule, PermissionModule, StorageModule],
|
||||
@@ -44,6 +44,7 @@ export class DocStorageWorkerModule {}
|
||||
|
||||
export {
|
||||
DatabaseDocReader,
|
||||
DocCreateIncompleteError,
|
||||
DocReader,
|
||||
DocStorageOptions,
|
||||
DocWriter,
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import type { Logger } from '@nestjs/common';
|
||||
import { mergeUpdates as yjsMergeUpdatesInCore } from 'yjs';
|
||||
|
||||
import { metrics } from '../../base';
|
||||
import { mergeUpdates as nativeMergeUpdates } from '../../native';
|
||||
|
||||
const SLOW_DOC_UPDATE_CODEC_MS = 250;
|
||||
|
||||
type CodecEngine = 'native' | 'yjs';
|
||||
type CodecEngine = 'native';
|
||||
type MetricStatus = 'ok' | 'error';
|
||||
|
||||
function recordCodecMetrics(
|
||||
@@ -96,18 +95,3 @@ export function mergeUpdatesWithNative(
|
||||
() => nativeMergeUpdates(updates.map(Buffer.from))
|
||||
);
|
||||
}
|
||||
|
||||
export function mergeUpdatesWithYjs(
|
||||
updates: Uint8Array[],
|
||||
caller: string,
|
||||
logger?: Pick<Logger, 'warn'>
|
||||
) {
|
||||
return measureSyncCodecOperation(
|
||||
'merge_updates',
|
||||
'yjs',
|
||||
updates,
|
||||
caller,
|
||||
logger,
|
||||
() => Buffer.from(yjsMergeUpdatesInCore(updates))
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { Injectable } from '@nestjs/common';
|
||||
|
||||
import { Config } from '../../base';
|
||||
import { QuotaService } from '../quota/service';
|
||||
import { mergeUpdatesWithNative, mergeUpdatesWithYjs } from './merge-updates';
|
||||
import { mergeUpdatesWithNative } from './merge-updates';
|
||||
import { DocStorageOptions as IDocStorageOptions } from './storage';
|
||||
|
||||
@Injectable()
|
||||
@@ -13,9 +13,7 @@ export class DocStorageOptions implements IDocStorageOptions {
|
||||
) {}
|
||||
|
||||
mergeUpdates = (updates: Uint8Array[]) =>
|
||||
this.config.doc.experimental.yocto
|
||||
? mergeUpdatesWithNative(updates, 'doc.options.merge_updates')
|
||||
: mergeUpdatesWithYjs(updates, 'doc.options.merge_updates');
|
||||
mergeUpdatesWithNative(updates, 'doc.options.merge_updates');
|
||||
|
||||
historyMaxAge = async (spaceId: string) => {
|
||||
const quota = await this.quota.getWorkspaceQuota(spaceId);
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import {
|
||||
applyUpdate,
|
||||
Array as YArray,
|
||||
diffUpdate,
|
||||
Doc as YDoc,
|
||||
encodeStateVectorFromUpdate,
|
||||
Map as YMap,
|
||||
} from 'yjs';
|
||||
|
||||
import { Cache } from '../../base';
|
||||
import { Models } from '../../models';
|
||||
import {
|
||||
diffDocUpdateV1,
|
||||
encodeStateVectorFromUpdateV1,
|
||||
extractRootDocIdAliases,
|
||||
} from '../../native';
|
||||
import { BackendRuntimeProvider } from '../backend-runtime';
|
||||
import { WorkspaceBlobStorage } from '../storage';
|
||||
import {
|
||||
@@ -174,11 +171,34 @@ export abstract class DocReader {
|
||||
): Promise<WorkspaceDocInfo | null>;
|
||||
|
||||
protected docDiff(update: Uint8Array, stateVector?: Uint8Array) {
|
||||
const missing = stateVector ? diffUpdate(update, stateVector) : update;
|
||||
const state = encodeStateVectorFromUpdate(update);
|
||||
const bin = Buffer.from(
|
||||
update.buffer,
|
||||
update.byteOffset,
|
||||
update.byteLength
|
||||
);
|
||||
const rawMissing =
|
||||
stateVector && stateVector.length > 0
|
||||
? diffDocUpdateV1(
|
||||
bin,
|
||||
Buffer.from(
|
||||
stateVector.buffer,
|
||||
stateVector.byteOffset,
|
||||
stateVector.byteLength
|
||||
)
|
||||
)
|
||||
: update;
|
||||
const rawState = encodeStateVectorFromUpdateV1(bin);
|
||||
return {
|
||||
missing,
|
||||
state,
|
||||
missing: new Uint8Array(
|
||||
rawMissing.buffer,
|
||||
rawMissing.byteOffset,
|
||||
rawMissing.byteLength
|
||||
),
|
||||
state: new Uint8Array(
|
||||
rawState.buffer,
|
||||
rawState.byteOffset,
|
||||
rawState.byteLength
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -206,22 +226,13 @@ export class DatabaseDocReader extends DocReader {
|
||||
? await this.workspace.getDoc(workspaceId, workspaceId)
|
||||
: rootDoc;
|
||||
if (!root) return aliases;
|
||||
const doc = new YDoc();
|
||||
try {
|
||||
applyUpdate(doc, root.bin);
|
||||
const pages = doc.getMap('meta').get('pages');
|
||||
if (!(pages instanceof YArray)) return aliases;
|
||||
const spaces = doc.getMap('spaces');
|
||||
for (const page of pages) {
|
||||
const id: unknown = page instanceof YMap ? page.get('id') : undefined;
|
||||
if (typeof id !== 'string') continue;
|
||||
const subdoc = spaces.get(id);
|
||||
if (subdoc instanceof YDoc) aliases.set(id, subdoc.guid);
|
||||
}
|
||||
return aliases;
|
||||
} finally {
|
||||
doc.destroy();
|
||||
const extracted = extractRootDocIdAliases(
|
||||
Buffer.from(root.bin.buffer, root.bin.byteOffset, root.bin.byteLength)
|
||||
);
|
||||
for (const [id, guid] of Object.entries(extracted)) {
|
||||
aliases.set(id, guid);
|
||||
}
|
||||
return aliases;
|
||||
}
|
||||
|
||||
async resolveStorageDocId(
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { Transactional } from '@nestjs-cls/transactional';
|
||||
import { TransactionalAdapterPrisma } from '@nestjs-cls/transactional-adapter-prisma';
|
||||
import { diffUpdate, encodeStateVectorFromUpdate } from 'yjs';
|
||||
|
||||
import {
|
||||
CallMetric,
|
||||
@@ -9,16 +8,20 @@ import {
|
||||
DocUpdateTooLarge,
|
||||
DocValidationUnavailable,
|
||||
} from '../../../base';
|
||||
import { validateDocUpdate } from '../../../native';
|
||||
import { mergeUpdatesWithYjs } from '../merge-updates';
|
||||
import {
|
||||
diffDocUpdateV1,
|
||||
encodeStateVectorFromUpdateV1,
|
||||
validateDocUpdate,
|
||||
} from '../../../native';
|
||||
import { mergeUpdatesWithNative } from '../merge-updates';
|
||||
import { Connection } from './connection';
|
||||
import { SingletonLocker } from './lock';
|
||||
|
||||
const DOC_UPDATE_VALIDATE_TIMEOUT_MS = 1000;
|
||||
const DOC_UPDATE_VALIDATE_MAX_BYTES = 32 * 1024 * 1024;
|
||||
|
||||
async function yjsMergeUpdates(updates: Uint8Array[]): Promise<Uint8Array> {
|
||||
return mergeUpdatesWithYjs(updates, 'doc.storage.squash.yjs');
|
||||
async function defaultMergeUpdates(updates: Uint8Array[]): Promise<Uint8Array> {
|
||||
return mergeUpdatesWithNative(updates, 'doc.storage.squash.native');
|
||||
}
|
||||
|
||||
export interface DocRecord {
|
||||
@@ -27,6 +30,7 @@ export interface DocRecord {
|
||||
bin: Uint8Array;
|
||||
timestamp: number;
|
||||
editor?: string;
|
||||
creator?: string;
|
||||
}
|
||||
|
||||
export interface DocDiff {
|
||||
@@ -61,7 +65,7 @@ export abstract class DocStorageAdapter extends Connection {
|
||||
|
||||
constructor(
|
||||
protected readonly options: DocStorageOptions = {
|
||||
mergeUpdates: yjsMergeUpdates,
|
||||
mergeUpdates: defaultMergeUpdates,
|
||||
}
|
||||
) {
|
||||
super();
|
||||
@@ -85,9 +89,12 @@ export abstract class DocStorageAdapter extends Connection {
|
||||
}
|
||||
let valid: boolean;
|
||||
try {
|
||||
valid = await validateDocUpdate(Buffer.from(update), {
|
||||
timeoutMs: DOC_UPDATE_VALIDATE_TIMEOUT_MS,
|
||||
});
|
||||
valid = await validateDocUpdate(
|
||||
Buffer.from(update.buffer, update.byteOffset, update.byteLength),
|
||||
{
|
||||
timeoutMs: DOC_UPDATE_VALIDATE_TIMEOUT_MS,
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
const unavailable = new DocValidationUnavailable();
|
||||
unavailable.cause = error;
|
||||
@@ -144,15 +151,19 @@ export abstract class DocStorageAdapter extends Connection {
|
||||
const timestamp = snapshot
|
||||
? Math.max(finalUpdate.timestamp, snapshot.timestamp + 1)
|
||||
: finalUpdate.timestamp;
|
||||
const fromInitialUpdates = snapshot === null;
|
||||
const newSnapshot: DocRecord = {
|
||||
spaceId,
|
||||
docId,
|
||||
bin,
|
||||
timestamp,
|
||||
editor,
|
||||
...(fromInitialUpdates ? { creator: updates[0]?.editor } : {}),
|
||||
};
|
||||
|
||||
const success = await this.setDocSnapshot(newSnapshot);
|
||||
const success = await this.setDocSnapshot(newSnapshot, {
|
||||
fromInitialUpdates,
|
||||
});
|
||||
|
||||
// if there is old snapshot, create a new history record
|
||||
if (success && snapshot) {
|
||||
@@ -180,12 +191,35 @@ export abstract class DocStorageAdapter extends Connection {
|
||||
return null;
|
||||
}
|
||||
|
||||
const missing = stateVector ? diffUpdate(doc.bin, stateVector) : doc.bin;
|
||||
const state = encodeStateVectorFromUpdate(doc.bin);
|
||||
const bin = Buffer.from(
|
||||
doc.bin.buffer,
|
||||
doc.bin.byteOffset,
|
||||
doc.bin.byteLength
|
||||
);
|
||||
const rawMissing =
|
||||
stateVector && stateVector.length > 0
|
||||
? diffDocUpdateV1(
|
||||
bin,
|
||||
Buffer.from(
|
||||
stateVector.buffer,
|
||||
stateVector.byteOffset,
|
||||
stateVector.byteLength
|
||||
)
|
||||
)
|
||||
: doc.bin;
|
||||
const rawState = encodeStateVectorFromUpdateV1(bin);
|
||||
|
||||
return {
|
||||
missing,
|
||||
state,
|
||||
missing: new Uint8Array(
|
||||
rawMissing.buffer,
|
||||
rawMissing.byteOffset,
|
||||
rawMissing.byteLength
|
||||
),
|
||||
state: new Uint8Array(
|
||||
rawState.buffer,
|
||||
rawState.byteOffset,
|
||||
rawState.byteLength
|
||||
),
|
||||
timestamp: doc.timestamp,
|
||||
};
|
||||
}
|
||||
@@ -197,14 +231,16 @@ export abstract class DocStorageAdapter extends Connection {
|
||||
editorId: string,
|
||||
expectedPermissionGeneration?: number,
|
||||
writeIntent?: 'update_doc' | 'create_doc',
|
||||
protocolVersion?: number
|
||||
protocolVersion?: number,
|
||||
expectedCurrentTimestamp?: number
|
||||
): Promise<{ timestamp: number; created: boolean }>;
|
||||
|
||||
abstract pushDocUpdatesTrusted(
|
||||
spaceId: string,
|
||||
docId: string,
|
||||
updates: Uint8Array[],
|
||||
editorId?: string
|
||||
editorId?: string,
|
||||
expectedCurrentTimestamp?: number
|
||||
): Promise<number>;
|
||||
|
||||
abstract deleteDoc(spaceId: string, docId: string): Promise<void>;
|
||||
@@ -229,7 +265,10 @@ export abstract class DocStorageAdapter extends Connection {
|
||||
spaceId: string,
|
||||
docId: string
|
||||
): Promise<DocRecord | null>;
|
||||
protected abstract setDocSnapshot(snapshot: DocRecord): Promise<boolean>;
|
||||
protected abstract setDocSnapshot(
|
||||
snapshot: DocRecord,
|
||||
options?: { fromInitialUpdates?: boolean }
|
||||
): Promise<boolean>;
|
||||
protected abstract getDocUpdates(
|
||||
spaceId: string,
|
||||
docId: string
|
||||
@@ -247,7 +286,7 @@ export abstract class DocStorageAdapter extends Connection {
|
||||
updates: DocUpdate[],
|
||||
merge?: (updates: Uint8Array[]) => Promise<Uint8Array>
|
||||
): Promise<DocUpdate> {
|
||||
const mergeFn = merge ?? this.options?.mergeUpdates ?? yjsMergeUpdates;
|
||||
const mergeFn = merge ?? this.options?.mergeUpdates ?? defaultMergeUpdates;
|
||||
const lastUpdate = updates.at(-1);
|
||||
if (!lastUpdate) {
|
||||
throw new Error('No updates to be squashed.');
|
||||
|
||||
@@ -1,30 +1,50 @@
|
||||
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
|
||||
import { nanoid } from 'nanoid';
|
||||
import {
|
||||
applyUpdate,
|
||||
Array as YArray,
|
||||
Doc as YDoc,
|
||||
encodeStateAsUpdate,
|
||||
encodeStateVector,
|
||||
Map as YMap,
|
||||
} from 'yjs';
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
Optional,
|
||||
} from '@nestjs/common';
|
||||
import { nanoid } from 'nanoid';
|
||||
|
||||
import { EventBus } from '../../base';
|
||||
import { EventBus, metrics, Mutex } from '../../base';
|
||||
import {
|
||||
addDocToRootDoc,
|
||||
createDocWithMarkdown,
|
||||
extractDocRecoveryFacts,
|
||||
isOrdinaryWorkspaceDoc,
|
||||
mergeUpdates,
|
||||
migrateRootDocPages,
|
||||
updateDocProperties,
|
||||
updateDocTitle,
|
||||
updateDocWithMarkdown,
|
||||
updateExistingRootDocMetaTitle,
|
||||
} from '../../native';
|
||||
import { BackendRuntimeProvider } from '../backend-runtime';
|
||||
import {
|
||||
backendRuntimeErrorCode,
|
||||
BackendRuntimeProvider,
|
||||
} from '../backend-runtime';
|
||||
import { PgWorkspaceDocStorageAdapter } from './adapters/workspace';
|
||||
import type { DocRecord } from './storage';
|
||||
|
||||
export interface CreateDocResult {
|
||||
docId: string;
|
||||
}
|
||||
|
||||
export class DocCreateIncompleteError extends Error {
|
||||
readonly docId: string;
|
||||
|
||||
constructor(docId: string, cause: unknown) {
|
||||
const causeMessage = cause instanceof Error ? cause.message : String(cause);
|
||||
super(
|
||||
`Document ${docId} created, but workspace registration failed: ${causeMessage}; retry with docId="${docId}" to finish registration`,
|
||||
{ cause }
|
||||
);
|
||||
this.name = 'DocCreateIncompleteError';
|
||||
this.docId = docId;
|
||||
}
|
||||
}
|
||||
|
||||
export interface UpdateDocResult {
|
||||
success: boolean;
|
||||
}
|
||||
@@ -42,6 +62,18 @@ declare global {
|
||||
}
|
||||
}
|
||||
|
||||
const errorMessage = (error: unknown) =>
|
||||
error instanceof Error ? error.message : String(error);
|
||||
|
||||
const isRevisionConflict = (error: unknown) =>
|
||||
backendRuntimeErrorCode(error) === 'doc_revision_conflict' ||
|
||||
errorMessage(error).includes('doc_revision_conflict');
|
||||
|
||||
const sleepBackoff = (attempt: number) =>
|
||||
new Promise<void>(resolve =>
|
||||
setTimeout(resolve, 10 + attempt * 15 + Math.floor(Math.random() * 20))
|
||||
);
|
||||
|
||||
@Injectable()
|
||||
export class DocWriter {
|
||||
private readonly logger = new Logger(DocWriter.name);
|
||||
@@ -49,7 +81,8 @@ export class DocWriter {
|
||||
constructor(
|
||||
private readonly storage: PgWorkspaceDocStorageAdapter,
|
||||
private readonly event: EventBus,
|
||||
private readonly runtime: BackendRuntimeProvider
|
||||
private readonly runtime: BackendRuntimeProvider,
|
||||
@Optional() private readonly mutex?: Mutex
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -95,36 +128,22 @@ export class DocWriter {
|
||||
editor: editorId,
|
||||
});
|
||||
|
||||
await this.updateDocProperties(
|
||||
workspaceId,
|
||||
docId,
|
||||
{
|
||||
createdBy: editorId,
|
||||
updatedBy: editorId,
|
||||
},
|
||||
editorId
|
||||
);
|
||||
|
||||
if (!(await this.runtime.getWorkspaceLifecycleActiveV1())) {
|
||||
const root = await this.storage.getDoc(workspaceId, workspaceId);
|
||||
const update = addDocToRootDoc(
|
||||
Buffer.from(root?.bin ?? [0, 0]),
|
||||
try {
|
||||
await this.updateDocProperties(
|
||||
workspaceId,
|
||||
docId,
|
||||
title
|
||||
);
|
||||
const { timestamp } = await this.storage.pushDocUpdates(
|
||||
workspaceId,
|
||||
workspaceId,
|
||||
[update],
|
||||
{
|
||||
createdBy: editorId,
|
||||
updatedBy: editorId,
|
||||
},
|
||||
editorId
|
||||
);
|
||||
this.emitDocUpdatesPushed({
|
||||
spaceId: workspaceId,
|
||||
docId: workspaceId,
|
||||
updates: [update],
|
||||
timestamp,
|
||||
editor: editorId,
|
||||
});
|
||||
|
||||
if (!(await this.runtime.getWorkspaceLifecycleActiveV1())) {
|
||||
await this.registerDocInRootDoc(workspaceId, docId, title, editorId);
|
||||
}
|
||||
} catch (error) {
|
||||
throw new DocCreateIncompleteError(docId, error);
|
||||
}
|
||||
|
||||
this.logger.debug(`Created doc ${docId} in workspace ${workspaceId}`);
|
||||
@@ -132,6 +151,115 @@ export class DocWriter {
|
||||
return { docId };
|
||||
}
|
||||
|
||||
/**
|
||||
* Idempotently completes properties & root-doc registration for an already-persisted
|
||||
* document whose creation failed partway through. Never creates new document content
|
||||
* and never overwrites existing `createdBy` / `updatedBy` metadata.
|
||||
*/
|
||||
async recoverDocCreation(
|
||||
workspaceId: string,
|
||||
docId: string,
|
||||
fallbackTitle: string,
|
||||
actorUserId: string
|
||||
): Promise<CreateDocResult> {
|
||||
const normalizedId = docId.trim();
|
||||
if (!normalizedId || !isOrdinaryWorkspaceDoc(workspaceId, normalizedId)) {
|
||||
throw new BadRequestException(`Invalid document ID: ${docId}`);
|
||||
}
|
||||
|
||||
const existing = await this.storage.getDoc(workspaceId, normalizedId);
|
||||
if (!existing?.bin || this.storage.isEmptyBin(existing.bin)) {
|
||||
throw new NotFoundException(`Document ${normalizedId} not found`);
|
||||
}
|
||||
|
||||
const toBuffer = (bin: Uint8Array) =>
|
||||
Buffer.isBuffer(bin)
|
||||
? bin
|
||||
: Buffer.from(bin.buffer, bin.byteOffset, bin.byteLength);
|
||||
|
||||
const docBuffer = toBuffer(existing.bin);
|
||||
const propertiesDocId = `db$${workspaceId}$docProperties`;
|
||||
const traceableCreator =
|
||||
existing.creator ??
|
||||
(await this.runtime.getWorkspaceDocCreatorV1?.(
|
||||
workspaceId,
|
||||
normalizedId
|
||||
)) ??
|
||||
undefined;
|
||||
const maxAttempts = 16;
|
||||
|
||||
try {
|
||||
let persistedTitle = '';
|
||||
let propertiesSynced = false;
|
||||
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
||||
const propertiesDoc = await this.storage.getDoc(
|
||||
workspaceId,
|
||||
propertiesDocId
|
||||
);
|
||||
const expectedPropsTs = propertiesDoc?.timestamp ?? 0;
|
||||
const facts = extractDocRecoveryFacts(
|
||||
docBuffer,
|
||||
propertiesDoc?.bin ? toBuffer(propertiesDoc.bin) : undefined,
|
||||
normalizedId
|
||||
);
|
||||
persistedTitle = facts.title;
|
||||
|
||||
const missingCreatedBy = facts.existingCreatedBy
|
||||
? undefined
|
||||
: traceableCreator;
|
||||
const missingUpdatedBy = facts.existingUpdatedBy
|
||||
? undefined
|
||||
: (existing.editor ?? traceableCreator);
|
||||
|
||||
if (!missingCreatedBy && !missingUpdatedBy) {
|
||||
propertiesSynced = true;
|
||||
break;
|
||||
}
|
||||
|
||||
try {
|
||||
await this.updateDocProperties(
|
||||
workspaceId,
|
||||
normalizedId,
|
||||
{
|
||||
createdBy: missingCreatedBy,
|
||||
updatedBy: missingUpdatedBy,
|
||||
},
|
||||
actorUserId,
|
||||
propertiesDoc,
|
||||
expectedPropsTs
|
||||
);
|
||||
propertiesSynced = true;
|
||||
break;
|
||||
} catch (error) {
|
||||
if (isRevisionConflict(error)) {
|
||||
await sleepBackoff(attempt);
|
||||
continue;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
if (!propertiesSynced) {
|
||||
throw new Error(
|
||||
`Failed to update properties for doc ${normalizedId} in workspace ${workspaceId} after ${maxAttempts} CAS attempts`
|
||||
);
|
||||
}
|
||||
|
||||
if (!(await this.runtime.getWorkspaceLifecycleActiveV1())) {
|
||||
await this.registerDocInRootDoc(
|
||||
workspaceId,
|
||||
normalizedId,
|
||||
persistedTitle || fallbackTitle,
|
||||
actorUserId
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
throw new DocCreateIncompleteError(normalizedId, error);
|
||||
}
|
||||
|
||||
return { docId: normalizedId };
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates an existing document with new markdown content.
|
||||
*
|
||||
@@ -234,19 +362,21 @@ export class DocWriter {
|
||||
existingDoc.bin.byteLength
|
||||
);
|
||||
const titleUpdate = updateDocTitle(existingBinary, meta.title, docId);
|
||||
const { timestamp: docTimestamp } = await this.storage.pushDocUpdates(
|
||||
workspaceId,
|
||||
docId,
|
||||
[titleUpdate],
|
||||
editorId
|
||||
);
|
||||
this.emitDocUpdatesPushed({
|
||||
spaceId: workspaceId,
|
||||
docId,
|
||||
updates: [titleUpdate],
|
||||
timestamp: docTimestamp,
|
||||
editor: editorId,
|
||||
});
|
||||
if (!this.storage.isEmptyBin(titleUpdate)) {
|
||||
const { timestamp: docTimestamp } = await this.storage.pushDocUpdates(
|
||||
workspaceId,
|
||||
docId,
|
||||
[titleUpdate],
|
||||
editorId
|
||||
);
|
||||
this.emitDocUpdatesPushed({
|
||||
spaceId: workspaceId,
|
||||
docId,
|
||||
updates: [titleUpdate],
|
||||
timestamp: docTimestamp,
|
||||
editor: editorId,
|
||||
});
|
||||
}
|
||||
|
||||
await this.updateDocProperties(
|
||||
workspaceId,
|
||||
@@ -258,44 +388,29 @@ export class DocWriter {
|
||||
if (!(await this.runtime.getWorkspaceLifecycleActiveV1())) {
|
||||
const root = await this.storage.getDoc(workspaceId, workspaceId);
|
||||
if (root) {
|
||||
const doc = new YDoc();
|
||||
try {
|
||||
applyUpdate(doc, root.bin);
|
||||
const pages = doc.getMap('meta').get('pages');
|
||||
const spaces = doc.getMap('spaces');
|
||||
const page =
|
||||
pages instanceof YArray
|
||||
? pages.toArray().find(page => {
|
||||
if (!(page instanceof YMap)) return false;
|
||||
const id = page.get('id');
|
||||
const subdoc =
|
||||
typeof id === 'string' ? spaces.get(id) : undefined;
|
||||
return (
|
||||
id === docId ||
|
||||
(subdoc instanceof YDoc && subdoc.guid === docId)
|
||||
);
|
||||
})
|
||||
: undefined;
|
||||
if (page instanceof YMap) {
|
||||
const state = encodeStateVector(doc);
|
||||
page.set('title', meta.title);
|
||||
const update = encodeStateAsUpdate(doc, state);
|
||||
const { timestamp } = await this.storage.pushDocUpdates(
|
||||
workspaceId,
|
||||
workspaceId,
|
||||
[update],
|
||||
editorId
|
||||
);
|
||||
this.emitDocUpdatesPushed({
|
||||
spaceId: workspaceId,
|
||||
docId: workspaceId,
|
||||
updates: [update],
|
||||
timestamp,
|
||||
editor: editorId,
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
doc.destroy();
|
||||
const update = updateExistingRootDocMetaTitle(
|
||||
Buffer.from(
|
||||
root.bin.buffer,
|
||||
root.bin.byteOffset,
|
||||
root.bin.byteLength
|
||||
),
|
||||
docId,
|
||||
meta.title
|
||||
);
|
||||
if (update && !this.storage.isEmptyBin(update)) {
|
||||
const { timestamp } = await this.storage.pushDocUpdates(
|
||||
workspaceId,
|
||||
workspaceId,
|
||||
[update],
|
||||
editorId
|
||||
);
|
||||
this.emitDocUpdatesPushed({
|
||||
spaceId: workspaceId,
|
||||
docId: workspaceId,
|
||||
updates: [update],
|
||||
timestamp,
|
||||
editor: editorId,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -303,6 +418,155 @@ export class DocWriter {
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
async registerDocInRootDoc(
|
||||
workspaceId: string,
|
||||
docId: string,
|
||||
title: string,
|
||||
editorId: string
|
||||
) {
|
||||
const toRootBuffer = (bin?: Uint8Array) =>
|
||||
bin
|
||||
? Buffer.from(bin.buffer, bin.byteOffset, bin.byteLength)
|
||||
: Buffer.from([0, 0]);
|
||||
|
||||
const maxAttempts = 16;
|
||||
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
||||
const root = await this.storage.getDoc(workspaceId, workspaceId);
|
||||
const expectedTs = root?.timestamp ?? 0;
|
||||
const rootBin = toRootBuffer(root?.bin);
|
||||
|
||||
let directUpdate: Uint8Array | null = null;
|
||||
let needsMigration = false;
|
||||
try {
|
||||
directUpdate = addDocToRootDoc(rootBin, docId, title);
|
||||
} catch (error) {
|
||||
if (!errorMessage(error).includes('invalid_root_shape')) {
|
||||
throw error;
|
||||
}
|
||||
needsMigration = true;
|
||||
}
|
||||
|
||||
if (!needsMigration) {
|
||||
if (!directUpdate || this.storage.isEmptyBin(directUpdate)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const { timestamp } = await this.storage.pushDocUpdates(
|
||||
workspaceId,
|
||||
workspaceId,
|
||||
[directUpdate],
|
||||
editorId,
|
||||
undefined,
|
||||
'update_doc',
|
||||
undefined,
|
||||
expectedTs
|
||||
);
|
||||
this.emitDocUpdatesPushed({
|
||||
spaceId: workspaceId,
|
||||
docId: workspaceId,
|
||||
updates: [directUpdate],
|
||||
timestamp,
|
||||
editor: editorId,
|
||||
});
|
||||
return;
|
||||
} catch (error) {
|
||||
if (isRevisionConflict(error)) {
|
||||
await sleepBackoff(attempt);
|
||||
continue;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
const executeMigration = async (): Promise<'done' | 'retry'> => {
|
||||
const latestRoot = await this.storage.getDoc(workspaceId, workspaceId);
|
||||
const latestExpectedTs = latestRoot?.timestamp ?? 0;
|
||||
const latestBin = toRootBuffer(latestRoot?.bin);
|
||||
|
||||
let batch: Uint8Array[];
|
||||
try {
|
||||
const migrationUpdate = latestRoot?.bin
|
||||
? migrateRootDocPages(latestBin)
|
||||
: null;
|
||||
const effectiveMigration =
|
||||
migrationUpdate && !this.storage.isEmptyBin(migrationUpdate)
|
||||
? migrationUpdate
|
||||
: null;
|
||||
const postMigrationBin = effectiveMigration
|
||||
? mergeUpdates([latestBin, effectiveMigration])
|
||||
: latestBin;
|
||||
const addUpdate = addDocToRootDoc(postMigrationBin, docId, title);
|
||||
batch = [
|
||||
...(effectiveMigration ? [effectiveMigration] : []),
|
||||
...(this.storage.isEmptyBin(addUpdate) ? [] : [addUpdate]),
|
||||
];
|
||||
} catch (migrationError) {
|
||||
const msg = errorMessage(migrationError);
|
||||
if (!msg.includes('invalid_root_shape')) {
|
||||
throw migrationError;
|
||||
}
|
||||
metrics.doc.counter('root_doc_register_skipped').add(1);
|
||||
this.logger.warn(
|
||||
`Skipped registering doc ${docId} in root doc for workspace ${workspaceId} after migration fallback failed: ${msg}`
|
||||
);
|
||||
return 'done';
|
||||
}
|
||||
|
||||
if (batch.length === 0) {
|
||||
return 'done';
|
||||
}
|
||||
|
||||
try {
|
||||
const { timestamp } = await this.storage.pushDocUpdates(
|
||||
workspaceId,
|
||||
workspaceId,
|
||||
batch,
|
||||
editorId,
|
||||
undefined,
|
||||
'update_doc',
|
||||
undefined,
|
||||
latestExpectedTs
|
||||
);
|
||||
this.emitDocUpdatesPushed({
|
||||
spaceId: workspaceId,
|
||||
docId: workspaceId,
|
||||
updates: batch,
|
||||
timestamp,
|
||||
editor: editorId,
|
||||
});
|
||||
return 'done';
|
||||
} catch (pushError) {
|
||||
if (isRevisionConflict(pushError)) {
|
||||
return 'retry';
|
||||
}
|
||||
throw pushError;
|
||||
}
|
||||
};
|
||||
|
||||
let outcome: 'done' | 'retry';
|
||||
if (this.mutex) {
|
||||
await using lock = await this.mutex.acquire(
|
||||
`doc:root-migration:${workspaceId}`
|
||||
);
|
||||
if (!lock) {
|
||||
await sleepBackoff(attempt);
|
||||
continue;
|
||||
}
|
||||
outcome = await executeMigration();
|
||||
} else {
|
||||
outcome = await executeMigration();
|
||||
}
|
||||
if (outcome === 'done') {
|
||||
return;
|
||||
}
|
||||
await sleepBackoff(attempt);
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`Failed to register doc ${docId} in root doc for workspace ${workspaceId} after ${maxAttempts} CAS attempts`
|
||||
);
|
||||
}
|
||||
|
||||
private emitDocUpdatesPushed(payload: {
|
||||
spaceId: string;
|
||||
docId: string;
|
||||
@@ -324,7 +588,9 @@ export class DocWriter {
|
||||
workspaceId: string,
|
||||
docId: string,
|
||||
props: { createdBy?: string; updatedBy?: string },
|
||||
editorId: string
|
||||
editorId: string,
|
||||
preloadedPropertiesDoc?: DocRecord | null,
|
||||
expectedCurrentTimestamp?: number
|
||||
) {
|
||||
if (!isOrdinaryWorkspaceDoc(workspaceId, docId)) {
|
||||
return;
|
||||
@@ -334,7 +600,10 @@ export class DocWriter {
|
||||
}
|
||||
|
||||
const propertiesDocId = `db$${workspaceId}$docProperties`;
|
||||
const existingDoc = await this.storage.getDoc(workspaceId, propertiesDocId);
|
||||
const existingDoc =
|
||||
preloadedPropertiesDoc !== undefined
|
||||
? preloadedPropertiesDoc
|
||||
: await this.storage.getDoc(workspaceId, propertiesDocId);
|
||||
const existingBinary = existingDoc?.bin
|
||||
? Buffer.isBuffer(existingDoc.bin)
|
||||
? existingDoc.bin
|
||||
@@ -360,7 +629,8 @@ export class DocWriter {
|
||||
workspaceId,
|
||||
propertiesDocId,
|
||||
[update],
|
||||
editorId
|
||||
editorId,
|
||||
expectedCurrentTimestamp
|
||||
);
|
||||
this.emitDocUpdatesPushed({
|
||||
spaceId: workspaceId,
|
||||
|
||||
@@ -210,6 +210,7 @@ declare global {
|
||||
updates: string[];
|
||||
timestamp: number;
|
||||
editor?: string;
|
||||
compressed?: boolean;
|
||||
};
|
||||
'sync.awareness.collect': SyncAwarenessEvent;
|
||||
'sync.awareness.updated': SyncAwarenessEvent & {
|
||||
@@ -913,6 +914,31 @@ export class SpaceSyncGateway
|
||||
|
||||
@OnEvent('sync.doc.updates.pushed')
|
||||
onClusterDocUpdatesPushed(payload: Events['sync.doc.updates.pushed']) {
|
||||
if (payload.compressed !== undefined) {
|
||||
const broadcastPayload: BroadcastDocUpdatesMessage = {
|
||||
spaceType: payload.spaceType,
|
||||
spaceId: payload.spaceId,
|
||||
docId: payload.docId,
|
||||
updates: payload.updates,
|
||||
timestamp: payload.timestamp,
|
||||
editor: payload.editor,
|
||||
compressed: payload.compressed,
|
||||
};
|
||||
this.emitActiveDocUpdate(
|
||||
{
|
||||
spaceType: payload.spaceType,
|
||||
spaceId: payload.spaceId,
|
||||
docId: payload.docId,
|
||||
updates: [],
|
||||
timestamp: payload.timestamp,
|
||||
editor: payload.editor,
|
||||
},
|
||||
undefined,
|
||||
broadcastPayload
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
this.emitActiveDocUpdate({
|
||||
...payload,
|
||||
updates: payload.updates.map(update =>
|
||||
@@ -1187,7 +1213,8 @@ export class SpaceSyncGateway
|
||||
});
|
||||
this.event.broadcast('sync.doc.updates.pushed', {
|
||||
...payload,
|
||||
updates: this.encodeUpdates(payload.updates),
|
||||
updates: broadcastPayload.updates,
|
||||
compressed: broadcastPayload.compressed,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { applyUpdate, Doc, encodeStateAsUpdate } from 'yjs';
|
||||
|
||||
import { canonicalizeDocumentIdentity } from '../../native';
|
||||
import { canonicalizeDocumentIdentity, mergeUpdates } from '../../native';
|
||||
|
||||
export class Guid1698398506533 {
|
||||
// do the migration
|
||||
@@ -63,10 +62,10 @@ export class Guid1698398506533 {
|
||||
}
|
||||
|
||||
// recover
|
||||
const yDoc = new Doc();
|
||||
applyUpdate(yDoc, toBeMergeUpdate.blob);
|
||||
applyUpdate(yDoc, existingUpdate.blob);
|
||||
const update = encodeStateAsUpdate(yDoc);
|
||||
const update = mergeUpdates([
|
||||
Buffer.from(toBeMergeUpdate.blob),
|
||||
Buffer.from(existingUpdate.blob),
|
||||
]);
|
||||
|
||||
await db.$transaction([
|
||||
// we already have 'xxx', delete 'space:xxx'
|
||||
|
||||
@@ -206,6 +206,19 @@ import type {
|
||||
} from './plugins/copilot/runtime/contracts/tool-contract';
|
||||
|
||||
export const mergeUpdates = serverNativeModule.mergeUpdates;
|
||||
export const diffDocUpdateV1 = serverNativeModule.diffDocUpdateV1;
|
||||
export const encodeStateVectorFromUpdateV1 =
|
||||
serverNativeModule.encodeStateVectorFromUpdateV1;
|
||||
export const extractDocRecoveryFacts =
|
||||
serverNativeModule.extractDocRecoveryFacts;
|
||||
export const extractRootDocIdAliases =
|
||||
serverNativeModule.extractRootDocIdAliases;
|
||||
export const extractWorkspaceLifecycleRootPages =
|
||||
serverNativeModule.extractWorkspaceLifecycleRootPages;
|
||||
export type {
|
||||
NativeDocRecoveryFacts,
|
||||
NativeLifecycleRootPage,
|
||||
} from '@affine/server-native';
|
||||
export const isOrdinaryWorkspaceDoc = serverNativeModule.isOrdinaryWorkspaceDoc;
|
||||
export const authorizeReservedDocSubject =
|
||||
serverNativeModule.authorizeReservedDocSubject;
|
||||
@@ -529,6 +542,9 @@ export const buildPublicRootDoc = serverNativeModule.buildPublicRootDoc;
|
||||
export const updateDocTitle = serverNativeModule.updateDocTitle;
|
||||
export const updateDocProperties = serverNativeModule.updateDocProperties;
|
||||
export const updateRootDocMetaTitle = serverNativeModule.updateRootDocMetaTitle;
|
||||
export const updateExistingRootDocMetaTitle =
|
||||
serverNativeModule.updateExistingRootDocMetaTitle;
|
||||
export const migrateRootDocPages = serverNativeModule.migrateRootDocPages;
|
||||
|
||||
const nativeLlmModule = serverNativeModule;
|
||||
|
||||
|
||||
@@ -2,8 +2,13 @@ import { Injectable } from '@nestjs/common';
|
||||
import { McpAccessMode } from '@prisma/client';
|
||||
import z from 'zod/v3';
|
||||
|
||||
import { DocReader, DocWriter } from '../../../core/doc';
|
||||
import {
|
||||
DocCreateIncompleteError,
|
||||
DocReader,
|
||||
DocWriter,
|
||||
} from '../../../core/doc';
|
||||
import { PermissionAccess } from '../../../core/permission';
|
||||
import { isOrdinaryWorkspaceDoc } from '../../../native';
|
||||
import { DocumentRetrievalService } from '../retrieval/document';
|
||||
|
||||
type McpTextContent = {
|
||||
@@ -214,6 +219,7 @@ export class WorkspaceMcpProvider {
|
||||
parser: z.object({
|
||||
title: z.string().min(1),
|
||||
content: z.string(),
|
||||
docId: z.string().trim().min(1).optional(),
|
||||
}),
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
@@ -226,11 +232,16 @@ export class WorkspaceMcpProvider {
|
||||
type: 'string',
|
||||
description: 'The markdown content for the document body',
|
||||
},
|
||||
docId: {
|
||||
type: 'string',
|
||||
description:
|
||||
'Optional document ID returned from a previous incomplete creation error; retries workspace registration idempotently without duplicating document content',
|
||||
},
|
||||
},
|
||||
required: ['title', 'content'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
execute: async ({ title, content }, options) => {
|
||||
execute: async ({ title, content, docId }, options) => {
|
||||
try {
|
||||
await this.ac
|
||||
.user(userId)
|
||||
@@ -241,25 +252,58 @@ export class WorkspaceMcpProvider {
|
||||
|
||||
const sanitizedTitle = title.replace(/[\r\n]+/g, ' ').trim();
|
||||
if (!sanitizedTitle) throw new Error('Title cannot be empty');
|
||||
const strippedContent = content.replace(
|
||||
/^[ \t]{0,3}#\s+[^\n]*#*\s*\n*/,
|
||||
''
|
||||
);
|
||||
const result = await this.writer.createDoc(
|
||||
workspaceId,
|
||||
sanitizedTitle,
|
||||
strippedContent,
|
||||
userId
|
||||
);
|
||||
|
||||
let result: { docId: string };
|
||||
if (docId !== undefined) {
|
||||
if (!isOrdinaryWorkspaceDoc(workspaceId, docId)) {
|
||||
return toolError('Invalid document ID.');
|
||||
}
|
||||
await this.ac
|
||||
.user(userId)
|
||||
.workspace(workspaceId)
|
||||
.doc(docId)
|
||||
.assert('Doc.Update');
|
||||
result = await this.writer.recoverDocCreation(
|
||||
workspaceId,
|
||||
docId,
|
||||
sanitizedTitle,
|
||||
userId
|
||||
);
|
||||
} else {
|
||||
const strippedContent = content.replace(
|
||||
/^[ \t]{0,3}#\s+[^\n]*#*\s*\n*/,
|
||||
''
|
||||
);
|
||||
result = await this.writer.createDoc(
|
||||
workspaceId,
|
||||
sanitizedTitle,
|
||||
strippedContent,
|
||||
userId
|
||||
);
|
||||
}
|
||||
|
||||
return toolText(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
docId: result.docId,
|
||||
message: `Document "${title}" created successfully`,
|
||||
message:
|
||||
docId !== undefined
|
||||
? `Document "${title}" registration completed`
|
||||
: `Document "${title}" created successfully`,
|
||||
})
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof DocCreateIncompleteError) {
|
||||
return toolError(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
code: 'doc_create_incomplete',
|
||||
retryable: true,
|
||||
docId: error.docId,
|
||||
message: error.message,
|
||||
})
|
||||
);
|
||||
}
|
||||
return toolError(
|
||||
`Failed to create document: ${error instanceof Error ? error.message : 'Unknown error'}`
|
||||
);
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { DocReader, DocWriter } from '../../../core/doc';
|
||||
import {
|
||||
DocCreateIncompleteError,
|
||||
DocReader,
|
||||
DocWriter,
|
||||
} from '../../../core/doc';
|
||||
import { PermissionAccess } from '../../../core/permission';
|
||||
import { isOrdinaryWorkspaceDoc } from '../../../native';
|
||||
import { toolError } from './error';
|
||||
import { defineTool } from './tool';
|
||||
import type { CopilotChatOptions } from './types';
|
||||
@@ -21,7 +26,8 @@ export const buildDocCreateHandler = (
|
||||
return async (
|
||||
options: CopilotChatOptions,
|
||||
title: string,
|
||||
content: string
|
||||
content: string,
|
||||
requestedDocId?: string
|
||||
) => {
|
||||
if (!options?.user || !options.workspace) {
|
||||
return toolError(
|
||||
@@ -35,23 +41,70 @@ export const buildDocCreateHandler = (
|
||||
return toolError('Doc Create Failed', 'Title cannot be empty');
|
||||
}
|
||||
|
||||
const strippedContent = stripLeadingH1(content);
|
||||
await ac
|
||||
.user(options.user)
|
||||
.workspace(options.workspace)
|
||||
.assert('Workspace.CreateDoc');
|
||||
const result = await writer.createDoc(
|
||||
options.workspace,
|
||||
sanitizedTitle,
|
||||
strippedContent,
|
||||
options.user
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
docId: result.docId,
|
||||
message: `Document "${sanitizedTitle}" created successfully`,
|
||||
};
|
||||
try {
|
||||
let result: { docId: string };
|
||||
let isRecovery = false;
|
||||
if (requestedDocId !== undefined) {
|
||||
isRecovery = true;
|
||||
const normalizedDocId = requestedDocId.trim();
|
||||
if (
|
||||
!normalizedDocId ||
|
||||
!isOrdinaryWorkspaceDoc(options.workspace, normalizedDocId)
|
||||
) {
|
||||
return toolError(
|
||||
'Doc Create Failed',
|
||||
`Invalid document ID: ${requestedDocId}`
|
||||
);
|
||||
}
|
||||
await ac
|
||||
.user(options.user)
|
||||
.workspace(options.workspace)
|
||||
.doc(normalizedDocId)
|
||||
.assert('Doc.Update');
|
||||
result = await writer.recoverDocCreation(
|
||||
options.workspace,
|
||||
normalizedDocId,
|
||||
sanitizedTitle,
|
||||
options.user
|
||||
);
|
||||
} else {
|
||||
const strippedContent = stripLeadingH1(content);
|
||||
result = await writer.createDoc(
|
||||
options.workspace,
|
||||
sanitizedTitle,
|
||||
strippedContent,
|
||||
options.user
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
docId: result.docId,
|
||||
message: isRecovery
|
||||
? `Document "${sanitizedTitle}" registration completed`
|
||||
: `Document "${sanitizedTitle}" created successfully`,
|
||||
};
|
||||
} catch (err) {
|
||||
if (err instanceof DocCreateIncompleteError) {
|
||||
const causeMessage =
|
||||
err.cause instanceof Error ? err.cause.message : err.message;
|
||||
return toolError(
|
||||
'Doc Create Failed',
|
||||
`Document ${err.docId} created, but workspace registration failed: ${causeMessage}; retry with doc_id="${err.docId}" to finish registration`,
|
||||
{
|
||||
code: 'doc_create_incomplete',
|
||||
retryable: true,
|
||||
locator: { doc_id: err.docId, docId: err.docId },
|
||||
}
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
@@ -140,20 +193,41 @@ export const buildDocUpdateMetaHandler = (
|
||||
};
|
||||
|
||||
export const createDocCreateTool = (
|
||||
createDoc: (title: string, content: string) => Promise<object>
|
||||
createDoc: (title: string, content: string, docId?: string) => Promise<object>
|
||||
) => {
|
||||
return defineTool({
|
||||
description:
|
||||
'Create a new document in the workspace with the given title and markdown content. Returns the ID of the created document. This tool not support insert or update database block and image yet.',
|
||||
inputSchema: z.object({
|
||||
title: z.string().min(1).describe('The title of the new document'),
|
||||
content: z
|
||||
.string()
|
||||
.describe('The markdown content for the document body'),
|
||||
}),
|
||||
execute: async ({ title, content }) => {
|
||||
inputSchema: z
|
||||
.object({
|
||||
title: z.string().min(1).describe('The title of the new document'),
|
||||
content: z
|
||||
.string()
|
||||
.describe('The markdown content for the document body'),
|
||||
doc_id: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe(
|
||||
'Optional document ID from an incomplete creation error to finish workspace registration without duplicating content'
|
||||
),
|
||||
docId: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe(
|
||||
'Alias of doc_id for retrying incomplete document creation'
|
||||
),
|
||||
})
|
||||
.strict()
|
||||
.refine(v => !v.doc_id || !v.docId || v.doc_id === v.docId, {
|
||||
message: 'doc_id and docId must match when both are provided',
|
||||
}),
|
||||
execute: async ({ title, content, doc_id, docId }) => {
|
||||
try {
|
||||
return await createDoc(title, content);
|
||||
return await createDoc(title, content, doc_id ?? docId);
|
||||
} catch (err: any) {
|
||||
logger.error(`Failed to create document: ${title}`, err);
|
||||
return toolError('Doc Create Failed', err.message);
|
||||
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
BlobRecord,
|
||||
CrawlResult,
|
||||
DocClock,
|
||||
DocDiff,
|
||||
DocIndexedClock,
|
||||
DocRecord,
|
||||
ListedBlobRecord,
|
||||
@@ -86,6 +87,12 @@ export interface NativeDBApis {
|
||||
docId: string
|
||||
) => Promise<void>;
|
||||
getDoc: (id: string, docId: string) => Promise<DocRecord | null>;
|
||||
getDocDiff?: (
|
||||
id: string,
|
||||
docId: string,
|
||||
state?: Uint8Array
|
||||
) => Promise<DocDiff | null>;
|
||||
mergeUpdates?: (updates: Uint8Array[]) => Promise<Uint8Array>;
|
||||
deleteDoc: (id: string, docId: string) => Promise<void>;
|
||||
getDocClocks: (id: string, after?: Date | null) => Promise<DocClock[]>;
|
||||
getDocClock: (id: string, docId: string) => Promise<DocClock | null>;
|
||||
@@ -193,13 +200,17 @@ export interface NativeDBApis {
|
||||
indexVersion: () => Promise<number>;
|
||||
}
|
||||
|
||||
type WrapApiFn<T> = T extends (...args: any[]) => any
|
||||
? Parameters<T> extends [string, ...infer Rest]
|
||||
? (...args: Rest) => ReturnType<T>
|
||||
: (...args: Parameters<T>) => ReturnType<T>
|
||||
: never;
|
||||
|
||||
type NativeDBApisWrapper = NativeDBApis extends infer APIs
|
||||
? {
|
||||
[K in keyof APIs]: APIs[K] extends (...args: any[]) => any
|
||||
? Parameters<APIs[K]> extends [string, ...infer Rest]
|
||||
? (...args: Rest) => ReturnType<APIs[K]>
|
||||
: (...args: Parameters<APIs[K]>) => ReturnType<APIs[K]>
|
||||
: never;
|
||||
[K in keyof APIs]: undefined extends APIs[K]
|
||||
? WrapApiFn<NonNullable<APIs[K]>> | undefined
|
||||
: WrapApiFn<APIs[K]>;
|
||||
}
|
||||
: never;
|
||||
|
||||
@@ -209,6 +220,12 @@ export function bindNativeDBApis(a: NativeDBApis) {
|
||||
apis = a;
|
||||
}
|
||||
|
||||
export function getNativeMergeUpdates():
|
||||
| ((updates: Uint8Array[]) => Promise<Uint8Array>)
|
||||
| undefined {
|
||||
return apis?.mergeUpdates;
|
||||
}
|
||||
|
||||
export class NativeDBConnection extends AutoReconnectConnection<void> {
|
||||
readonly apis: NativeDBApisWrapper;
|
||||
|
||||
@@ -241,6 +258,15 @@ export class NativeDBConnection extends AutoReconnectConnection<void> {
|
||||
{
|
||||
get: (_target, key: keyof NativeDBApisWrapper) => {
|
||||
const v = originalApis[key];
|
||||
if (typeof v !== 'function') {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (key === 'mergeUpdates' || key === 'indexVersion') {
|
||||
return async (...args: any[]) => {
|
||||
return (v as (...a: any[]) => any).apply(originalApis, args);
|
||||
};
|
||||
}
|
||||
|
||||
return async (...args: any[]) => {
|
||||
return v.call(
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import {
|
||||
applyUpdate,
|
||||
Doc as YDoc,
|
||||
encodeStateAsUpdate,
|
||||
encodeStateVector,
|
||||
} from 'yjs';
|
||||
|
||||
import type { DocDiff, DocRecord } from '../../storage';
|
||||
import { bindNativeDBApis, type NativeDBApis } from './db';
|
||||
import { SqliteDocStorage } from './doc';
|
||||
|
||||
function createBaseApis(overrides: Partial<NativeDBApis> = {}): NativeDBApis {
|
||||
const unimplemented = async () => {
|
||||
throw new Error('not implemented in test');
|
||||
};
|
||||
return {
|
||||
connect: async () => {},
|
||||
disconnect: async () => {},
|
||||
pushUpdate: unimplemented,
|
||||
getPeerWorkspaceState: unimplemented,
|
||||
invalidatePeerWorkspaceState: unimplemented,
|
||||
installPeerWorkspaceState: unimplemented,
|
||||
confirmPeerDocCreate: unimplemented,
|
||||
getDoc: async () => null,
|
||||
deleteDoc: unimplemented,
|
||||
getDocClocks: unimplemented,
|
||||
getDocClock: unimplemented,
|
||||
getDocIndexedClock: unimplemented,
|
||||
setDocIndexedClock: unimplemented,
|
||||
setDocIndexedClocks: unimplemented,
|
||||
clearDocIndexedClock: unimplemented,
|
||||
getBlob: unimplemented,
|
||||
setBlob: unimplemented,
|
||||
deleteBlob: unimplemented,
|
||||
releaseBlobs: unimplemented,
|
||||
listBlobs: unimplemented,
|
||||
getPeerRemoteClocks: unimplemented,
|
||||
getPeerRemoteClock: unimplemented,
|
||||
setPeerRemoteClock: unimplemented,
|
||||
getPeerPulledRemoteClocks: unimplemented,
|
||||
getPeerPulledRemoteClock: unimplemented,
|
||||
setPeerPulledRemoteClock: unimplemented,
|
||||
getPeerPushedClocks: unimplemented,
|
||||
getPeerPushedClock: unimplemented,
|
||||
setPeerPushedClock: unimplemented,
|
||||
clearClocks: unimplemented,
|
||||
setBlobUploadedAt: unimplemented,
|
||||
getBlobUploadedAt: unimplemented,
|
||||
crawlDocData: unimplemented,
|
||||
indexUpsert: unimplemented,
|
||||
indexDelete: unimplemented,
|
||||
indexSearch: unimplemented,
|
||||
indexAggregate: unimplemented,
|
||||
indexDeleteByQuery: unimplemented,
|
||||
indexFlush: unimplemented,
|
||||
indexVersion: unimplemented,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('SqliteDocStorage.getDocDiff', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
test('delegates directly to native getDocDiff when implemented', async () => {
|
||||
const doc = new YDoc();
|
||||
doc.getText('content').insert(0, 'hello');
|
||||
const sv1 = encodeStateVector(doc);
|
||||
doc.getText('content').insert(5, ' world');
|
||||
const fullUpdate = encodeStateAsUpdate(doc);
|
||||
const fullSv = encodeStateVector(doc);
|
||||
const diffUpdate = encodeStateAsUpdate(doc, sv1);
|
||||
const ts = new Date('2026-01-01T00:00:00.000Z');
|
||||
|
||||
const getDoc = vi.fn(async () => {
|
||||
throw new Error(
|
||||
'getDoc should not be called when native getDocDiff is present'
|
||||
);
|
||||
});
|
||||
const getDocDiff = vi.fn(
|
||||
async (
|
||||
_id: string,
|
||||
docId: string,
|
||||
state?: Uint8Array
|
||||
): Promise<DocDiff | null> => {
|
||||
if (docId === 'missing') return null;
|
||||
if (!state || state.length === 0) {
|
||||
return { docId, missing: fullUpdate, state: fullSv, timestamp: ts };
|
||||
}
|
||||
return { docId, missing: diffUpdate, state: fullSv, timestamp: ts };
|
||||
}
|
||||
);
|
||||
|
||||
bindNativeDBApis(createBaseApis({ getDoc, getDocDiff }));
|
||||
|
||||
const storage = new SqliteDocStorage({
|
||||
flavour: 'local',
|
||||
type: 'workspace',
|
||||
id: 'ws-native-diff',
|
||||
});
|
||||
|
||||
expect(await storage.getDocDiff('missing')).toBeNull();
|
||||
|
||||
const full1 = await storage.getDocDiff('doc-1');
|
||||
expect(full1).toEqual({
|
||||
docId: 'doc-1',
|
||||
missing: fullUpdate,
|
||||
state: fullSv,
|
||||
timestamp: ts,
|
||||
});
|
||||
|
||||
const full2 = await storage.getDocDiff('doc-1', new Uint8Array(0));
|
||||
expect(full2?.missing).toEqual(fullUpdate);
|
||||
|
||||
const inc = await storage.getDocDiff('doc-1', sv1);
|
||||
expect(inc?.missing).toEqual(diffUpdate);
|
||||
expect(inc?.state).toEqual(fullSv);
|
||||
|
||||
expect(getDoc).not.toHaveBeenCalled();
|
||||
expect(getDocDiff).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
|
||||
test('falls back to DocStorageBase.getDocDiff when native getDocDiff is omitted', async () => {
|
||||
const doc = new YDoc();
|
||||
doc.getText('content').insert(0, 'alpha');
|
||||
const sv1 = encodeStateVector(doc);
|
||||
doc.getText('content').insert(5, ' beta');
|
||||
const fullUpdate = encodeStateAsUpdate(doc);
|
||||
const ts = new Date('2026-01-02T00:00:00.000Z');
|
||||
|
||||
const getDoc = vi.fn(
|
||||
async (_id: string, docId: string): Promise<DocRecord | null> => {
|
||||
if (docId !== 'doc-fallback') return null;
|
||||
return { docId, bin: fullUpdate, timestamp: ts };
|
||||
}
|
||||
);
|
||||
|
||||
bindNativeDBApis(createBaseApis({ getDoc }));
|
||||
|
||||
const storage = new SqliteDocStorage({
|
||||
flavour: 'local',
|
||||
type: 'workspace',
|
||||
id: 'ws-fallback-diff',
|
||||
});
|
||||
|
||||
expect(await storage.getDocDiff('missing')).toBeNull();
|
||||
|
||||
const zeroDiff = await storage.getDocDiff(
|
||||
'doc-fallback',
|
||||
new Uint8Array([0])
|
||||
);
|
||||
expect(zeroDiff).not.toBeNull();
|
||||
const restoredZero = new YDoc();
|
||||
applyUpdate(restoredZero, zeroDiff!.missing);
|
||||
expect(restoredZero.getText('content').toString()).toBe('alpha beta');
|
||||
|
||||
const inc = await storage.getDocDiff('doc-fallback', sv1);
|
||||
expect(inc).not.toBeNull();
|
||||
expect(inc!.timestamp).toEqual(ts);
|
||||
expect(getDoc).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
});
|
||||
@@ -20,6 +20,13 @@ export class SqliteDocStorage extends DocStorageBase<SqliteNativeDBOptions> {
|
||||
return this.db.getDoc(docId);
|
||||
}
|
||||
|
||||
override async getDocDiff(docId: string, state?: Uint8Array) {
|
||||
if (this.db.getDocDiff) {
|
||||
return this.db.getDocDiff(docId, state);
|
||||
}
|
||||
return super.getDocDiff(docId, state);
|
||||
}
|
||||
|
||||
override async pushDocUpdate(update: DocUpdate, origin?: string) {
|
||||
const createForPeer =
|
||||
update.createForPeer ??
|
||||
|
||||
@@ -10,6 +10,7 @@ export * from './blob';
|
||||
export * from './blob-sync';
|
||||
export {
|
||||
bindNativeDBApis,
|
||||
getNativeMergeUpdates,
|
||||
type NativeDBApis,
|
||||
type NativeIndexField,
|
||||
type NativeIndexHit,
|
||||
|
||||
@@ -85,6 +85,7 @@ export class DocSyncImpl implements DocSync {
|
||||
) ??
|
||||
new DocSyncPeer(id, this.storages.local, this.sync, remote, {
|
||||
isDeleted: docId => this.isDeleted(docId),
|
||||
mergeUpdates: this.options?.mergeUpdates,
|
||||
})
|
||||
)
|
||||
);
|
||||
@@ -160,7 +161,12 @@ export class DocSyncImpl implements DocSync {
|
||||
|
||||
constructor(
|
||||
readonly storages: PeerStorageOptions<DocStorage>,
|
||||
readonly sync: DocSyncStorage
|
||||
readonly sync: DocSyncStorage,
|
||||
private readonly options?: {
|
||||
mergeUpdates?: (
|
||||
updates: Uint8Array[]
|
||||
) => Promise<Uint8Array> | Uint8Array;
|
||||
}
|
||||
) {
|
||||
this.setRemotes(storages.remotes);
|
||||
}
|
||||
|
||||
@@ -573,12 +573,10 @@ export class DocSyncPeer {
|
||||
);
|
||||
|
||||
if (jobs.some(job => job.update && !isEmptyUpdate(job.update))) {
|
||||
const local = await this.local.getDoc(docId);
|
||||
if (local) {
|
||||
const remoteState = this.status.remoteStateVectors.get(docId);
|
||||
const update = remoteState
|
||||
? diffUpdate(local.bin, remoteState)
|
||||
: local.bin;
|
||||
const remoteState = this.status.remoteStateVectors.get(docId);
|
||||
const diff = await this.local.getDocDiff(docId, remoteState);
|
||||
if (diff) {
|
||||
const update = diff.missing;
|
||||
if (!isEmptyUpdate(update)) {
|
||||
const { timestamp } = await this.pushRemote({
|
||||
docId,
|
||||
@@ -586,13 +584,10 @@ export class DocSyncPeer {
|
||||
});
|
||||
this.schedule({ type: 'save', docId, remoteClock: timestamp });
|
||||
}
|
||||
this.status.remoteStateVectors.set(
|
||||
docId,
|
||||
encodeStateVectorFromUpdate(local.bin)
|
||||
);
|
||||
this.status.remoteStateVectors.set(docId, diff.state);
|
||||
await this.syncMetadata.setPeerPushedClock(this.metadataPeer, {
|
||||
docId,
|
||||
timestamp: local.timestamp,
|
||||
timestamp: diff.timestamp,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -19,6 +19,10 @@ export interface SyncState {
|
||||
doc?: DocSyncState;
|
||||
}
|
||||
|
||||
export interface SyncOptions {
|
||||
mergeUpdates?: (updates: Uint8Array[]) => Promise<Uint8Array> | Uint8Array;
|
||||
}
|
||||
|
||||
export class Sync {
|
||||
readonly doc: DocSyncImpl;
|
||||
readonly blob: BlobSyncImpl;
|
||||
@@ -27,7 +31,10 @@ export class Sync {
|
||||
|
||||
readonly state$: Observable<SyncState>;
|
||||
|
||||
constructor(readonly storages: PeerStorageOptions<SpaceStorage>) {
|
||||
constructor(
|
||||
readonly storages: PeerStorageOptions<SpaceStorage>,
|
||||
options?: SyncOptions
|
||||
) {
|
||||
const doc = storages.local.get('doc');
|
||||
const blob = storages.local.get('blob');
|
||||
const docSync = storages.local.get('docSync');
|
||||
@@ -46,7 +53,8 @@ export class Sync {
|
||||
])
|
||||
),
|
||||
},
|
||||
docSync
|
||||
docSync,
|
||||
{ mergeUpdates: options?.mergeUpdates }
|
||||
);
|
||||
this.blob = new BlobSyncImpl(
|
||||
{
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
import 'fake-indexeddb/auto';
|
||||
|
||||
import { OpClient, OpConsumer } from '@toeverything/infra/op';
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import {
|
||||
applyUpdate,
|
||||
diffUpdate,
|
||||
Doc as YDoc,
|
||||
encodeStateAsUpdate,
|
||||
encodeStateVector,
|
||||
mergeUpdates as yjsMergeUpdates,
|
||||
} from 'yjs';
|
||||
|
||||
import { DummyConnection } from '../../connection';
|
||||
import type { StorageConstructor } from '../../impls';
|
||||
import {
|
||||
bindNativeDBApis,
|
||||
type NativeDBApis,
|
||||
SqliteDocStorage,
|
||||
} from '../../impls/sqlite';
|
||||
import {
|
||||
type DocClock,
|
||||
type DocClocks,
|
||||
type DocDiff,
|
||||
type DocRecord,
|
||||
DocStorageBase,
|
||||
type DocUpdate,
|
||||
} from '../../storage';
|
||||
import { DummyDocSyncStorage } from '../../storage/dummy/doc-sync';
|
||||
import { StoreManagerClient } from '../client';
|
||||
import { StoreManagerConsumer } from '../consumer';
|
||||
import type { WorkerManagerOps } from '../ops';
|
||||
|
||||
class InMemoryRemoteDocStorage extends DocStorageBase {
|
||||
static readonly identifier = 'TestRemoteDocStorage';
|
||||
override connection = new DummyConnection();
|
||||
private readonly docs = new Map<string, DocRecord>();
|
||||
|
||||
override async getDoc(docId: string): Promise<DocRecord | null> {
|
||||
return this.docs.get(docId) ?? null;
|
||||
}
|
||||
|
||||
override async pushDocUpdate(
|
||||
update: DocUpdate,
|
||||
origin?: string
|
||||
): Promise<DocClock> {
|
||||
const prev = this.docs.get(update.docId);
|
||||
const bin = prev ? yjsMergeUpdates([prev.bin, update.bin]) : update.bin;
|
||||
const timestamp = new Date(Date.now());
|
||||
const record: DocRecord = {
|
||||
docId: update.docId,
|
||||
bin,
|
||||
timestamp,
|
||||
editor: update.editor,
|
||||
};
|
||||
this.docs.set(update.docId, record);
|
||||
this.emit('update', record, origin);
|
||||
return { docId: update.docId, timestamp };
|
||||
}
|
||||
|
||||
override async getDocTimestamp(docId: string): Promise<DocClock | null> {
|
||||
const rec = this.docs.get(docId);
|
||||
return rec ? { docId, timestamp: rec.timestamp } : null;
|
||||
}
|
||||
|
||||
override async getDocTimestamps(): Promise<DocClocks> {
|
||||
const clocks: DocClocks = {};
|
||||
for (const [docId, rec] of this.docs.entries()) {
|
||||
clocks[docId] = rec.timestamp;
|
||||
}
|
||||
return clocks;
|
||||
}
|
||||
|
||||
override async deleteDoc(docId: string): Promise<void> {
|
||||
this.docs.delete(docId);
|
||||
}
|
||||
}
|
||||
|
||||
class TestDummyDocSyncStorage extends DummyDocSyncStorage {
|
||||
static readonly identifier = 'TestDummyDocSyncStorage';
|
||||
}
|
||||
|
||||
function createFakeNativeDBApis(
|
||||
onGetDocDiff: (...args: unknown[]) => void,
|
||||
onMergeUpdates: (...args: unknown[]) => void
|
||||
): NativeDBApis {
|
||||
const docs = new Map<string, { bin: Uint8Array; timestamp: Date }>();
|
||||
let clockMs = 1_700_000_000_000;
|
||||
const unimplemented = async () => {
|
||||
throw new Error('not implemented in test');
|
||||
};
|
||||
|
||||
return {
|
||||
connect: async () => {},
|
||||
disconnect: async () => {},
|
||||
pushUpdate: async (_id, docId, update) => {
|
||||
const prev = docs.get(docId);
|
||||
const bin = prev ? yjsMergeUpdates([prev.bin, update]) : update;
|
||||
clockMs += 10;
|
||||
const timestamp = new Date(clockMs);
|
||||
docs.set(docId, { bin, timestamp });
|
||||
return timestamp;
|
||||
},
|
||||
getPeerWorkspaceState: unimplemented,
|
||||
invalidatePeerWorkspaceState: unimplemented,
|
||||
installPeerWorkspaceState: unimplemented,
|
||||
confirmPeerDocCreate: unimplemented,
|
||||
getDoc: async (_id, docId) => {
|
||||
const rec = docs.get(docId);
|
||||
return rec ? { docId, bin: rec.bin, timestamp: rec.timestamp } : null;
|
||||
},
|
||||
getDocDiff: async (id, docId, state): Promise<DocDiff | null> => {
|
||||
onGetDocDiff(id, docId, state);
|
||||
const rec = docs.get(docId);
|
||||
if (!rec) return null;
|
||||
const missing =
|
||||
state && state.length > 0 ? diffUpdate(rec.bin, state) : rec.bin;
|
||||
const fullState = encodeStateVector(
|
||||
(() => {
|
||||
const d = new YDoc();
|
||||
applyUpdate(d, rec.bin);
|
||||
return d;
|
||||
})()
|
||||
);
|
||||
return {
|
||||
docId,
|
||||
missing,
|
||||
state: fullState,
|
||||
timestamp: rec.timestamp,
|
||||
};
|
||||
},
|
||||
mergeUpdates: async updates => {
|
||||
onMergeUpdates(updates);
|
||||
return yjsMergeUpdates(updates);
|
||||
},
|
||||
deleteDoc: async (_id, docId) => {
|
||||
docs.delete(docId);
|
||||
},
|
||||
getDocClocks: async () =>
|
||||
Array.from(docs.entries()).map(([docId, rec]) => ({
|
||||
docId,
|
||||
timestamp: rec.timestamp,
|
||||
})),
|
||||
getDocClock: async (_id, docId) => {
|
||||
const rec = docs.get(docId);
|
||||
return rec ? { docId, timestamp: rec.timestamp } : null;
|
||||
},
|
||||
getDocIndexedClock: unimplemented,
|
||||
setDocIndexedClock: unimplemented,
|
||||
setDocIndexedClocks: unimplemented,
|
||||
clearDocIndexedClock: unimplemented,
|
||||
getBlob: unimplemented,
|
||||
setBlob: unimplemented,
|
||||
deleteBlob: unimplemented,
|
||||
releaseBlobs: unimplemented,
|
||||
listBlobs: unimplemented,
|
||||
getPeerRemoteClocks: async () => [],
|
||||
getPeerRemoteClock: async () => null,
|
||||
setPeerRemoteClock: async () => {},
|
||||
getPeerPulledRemoteClocks: async () => [],
|
||||
getPeerPulledRemoteClock: async () => null,
|
||||
setPeerPulledRemoteClock: async () => {},
|
||||
getPeerPushedClocks: async () => [],
|
||||
getPeerPushedClock: async () => null,
|
||||
setPeerPushedClock: async () => {},
|
||||
clearClocks: async () => {},
|
||||
setBlobUploadedAt: unimplemented,
|
||||
getBlobUploadedAt: unimplemented,
|
||||
crawlDocData: unimplemented,
|
||||
indexUpsert: unimplemented,
|
||||
indexDelete: unimplemented,
|
||||
indexSearch: unimplemented,
|
||||
indexAggregate: unimplemented,
|
||||
indexDeleteByQuery: unimplemented,
|
||||
indexFlush: unimplemented,
|
||||
indexVersion: unimplemented,
|
||||
};
|
||||
}
|
||||
|
||||
describe('StoreManagerClient + StoreManagerConsumer native sync wiring', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
test('DocFrontend uses injected native mergeUpdates and DocPeer push uses SqliteDocStorage.getDocDiff', async () => {
|
||||
const nativeGetDocDiff = vi.fn();
|
||||
const nativeMergeUpdates = vi.fn();
|
||||
const nativeApis = createFakeNativeDBApis(
|
||||
nativeGetDocDiff,
|
||||
nativeMergeUpdates
|
||||
);
|
||||
const seedDoc = new YDoc({ guid: 'doc-1' });
|
||||
seedDoc.getText('content').insert(0, 'seed');
|
||||
await nativeApis.pushUpdate(
|
||||
'local:workspace:ws-1',
|
||||
'doc-1',
|
||||
encodeStateAsUpdate(seedDoc)
|
||||
);
|
||||
bindNativeDBApis(nativeApis);
|
||||
|
||||
const { port1, port2 } = new MessageChannel();
|
||||
port1.start();
|
||||
port2.start();
|
||||
const consumer = new OpConsumer<WorkerManagerOps>(port2);
|
||||
const managerConsumer = new StoreManagerConsumer(
|
||||
[
|
||||
SqliteDocStorage,
|
||||
TestDummyDocSyncStorage,
|
||||
InMemoryRemoteDocStorage,
|
||||
] as unknown as StorageConstructor[],
|
||||
{ mergeUpdates: nativeApis.mergeUpdates }
|
||||
);
|
||||
managerConsumer.bindConsumer(consumer);
|
||||
|
||||
const managerClient = new StoreManagerClient(
|
||||
new OpClient<WorkerManagerOps>(port1),
|
||||
{ mergeUpdates: nativeApis.mergeUpdates }
|
||||
);
|
||||
|
||||
const { store, dispose } = managerClient.open('test-native-sync', {
|
||||
local: {
|
||||
doc: {
|
||||
name: SqliteDocStorage.identifier,
|
||||
opts: { flavour: 'local', type: 'workspace', id: 'ws-1' },
|
||||
},
|
||||
docSync: {
|
||||
name: TestDummyDocSyncStorage.identifier,
|
||||
opts: { id: 'ws-1' },
|
||||
},
|
||||
},
|
||||
remotes: {
|
||||
cloud: {
|
||||
doc: {
|
||||
name: InMemoryRemoteDocStorage.identifier,
|
||||
opts: { id: 'ws-1' },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const ydoc = new YDoc({ guid: 'doc-1' });
|
||||
store.docFrontend.connectDoc(ydoc);
|
||||
store.docFrontend.start();
|
||||
await store.docFrontend.waitForDocReady('doc-1');
|
||||
await store.docFrontend.waitForSynced('doc-1');
|
||||
|
||||
// Apply multiple updates in one tick so DocFrontend coalesces them through mergeUpdates.
|
||||
ydoc.getText('content').insert(0, 'hello');
|
||||
ydoc.getText('content').insert(5, ' native');
|
||||
ydoc.getText('content').insert(12, ' sync');
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(nativeMergeUpdates).toHaveBeenCalled();
|
||||
expect(nativeGetDocDiff).toHaveBeenCalled();
|
||||
expect(
|
||||
nativeGetDocDiff.mock.calls.some(call => call[1] === 'doc-1')
|
||||
).toBe(true);
|
||||
},
|
||||
{ timeout: 10_000 }
|
||||
);
|
||||
} finally {
|
||||
store.docFrontend.stop();
|
||||
dispose();
|
||||
managerClient.dispose();
|
||||
consumer.destroy();
|
||||
port1.close();
|
||||
port2.close();
|
||||
}
|
||||
}, 15_000);
|
||||
});
|
||||
@@ -76,6 +76,10 @@ function realtimeAbortError(op: RealtimeRequestName) {
|
||||
return error;
|
||||
}
|
||||
|
||||
export interface StoreManagerClientOptions {
|
||||
mergeUpdates?: (updates: Uint8Array[]) => Promise<Uint8Array> | Uint8Array;
|
||||
}
|
||||
|
||||
export class StoreManagerClient {
|
||||
private readonly connections = new Map<
|
||||
string,
|
||||
@@ -85,7 +89,10 @@ export class StoreManagerClient {
|
||||
}
|
||||
>();
|
||||
|
||||
constructor(private readonly client: OpClient<WorkerManagerOps>) {
|
||||
constructor(
|
||||
private readonly client: OpClient<WorkerManagerOps>,
|
||||
private readonly options?: StoreManagerClientOptions
|
||||
) {
|
||||
this.telemetry = new TelemetryClient(this.client);
|
||||
this.realtime = new RealtimeClient(this.client);
|
||||
}
|
||||
@@ -117,7 +124,7 @@ export class StoreManagerClient {
|
||||
});
|
||||
|
||||
const connection = {
|
||||
store: new StoreClient(client),
|
||||
store: new StoreClient(client, this.options),
|
||||
dispose: () => {
|
||||
this.client.call('close', closeKey).catch(err => {
|
||||
console.error('error closing', err);
|
||||
@@ -235,13 +242,18 @@ export class RealtimeClient {
|
||||
}
|
||||
|
||||
export class StoreClient {
|
||||
constructor(private readonly client: OpClient<WorkerOps>) {
|
||||
constructor(
|
||||
private readonly client: OpClient<WorkerOps>,
|
||||
options?: StoreManagerClientOptions
|
||||
) {
|
||||
this.docStorage = new WorkerDocStorage(this.client);
|
||||
this.blobStorage = new WorkerBlobStorage(this.client);
|
||||
this.docSync = new WorkerDocSync(this.client);
|
||||
this.blobSync = new WorkerBlobSync(this.client);
|
||||
this.awarenessSync = new WorkerAwarenessSync(this.client);
|
||||
this.docFrontend = new DocFrontend(this.docStorage, this.docSync);
|
||||
this.docFrontend = new DocFrontend(this.docStorage, this.docSync, {
|
||||
mergeUpdates: options?.mergeUpdates,
|
||||
});
|
||||
this.blobFrontend = new BlobFrontend(this.blobStorage, this.blobSync);
|
||||
this.awarenessFrontend = new AwarenessFrontend(this.awarenessSync);
|
||||
this.indexerSync = new WorkerIndexerSync(this.client);
|
||||
|
||||
@@ -8,6 +8,10 @@ import { StoreConsumer } from './store';
|
||||
|
||||
export type { WorkerManagerOps };
|
||||
|
||||
export interface StoreManagerConsumerOptions {
|
||||
mergeUpdates?: (updates: Uint8Array[]) => Promise<Uint8Array> | Uint8Array;
|
||||
}
|
||||
|
||||
export class StoreManagerConsumer {
|
||||
private readonly storeDisposers = new Map<string, () => Promise<void>>();
|
||||
private readonly storePool = new Map<
|
||||
@@ -34,7 +38,8 @@ export class StoreManagerConsumer {
|
||||
private readonly realtime = new RealtimeManager();
|
||||
|
||||
constructor(
|
||||
private readonly availableStorageImplementations: StorageConstructor[]
|
||||
private readonly availableStorageImplementations: StorageConstructor[],
|
||||
private readonly options?: StoreManagerConsumerOptions
|
||||
) {}
|
||||
|
||||
bindConsumer(consumer: OpConsumer<WorkerManagerOps>) {
|
||||
@@ -51,7 +56,8 @@ export class StoreManagerConsumer {
|
||||
entry = {
|
||||
store: new StoreConsumer(
|
||||
this.availableStorageImplementations,
|
||||
options
|
||||
options,
|
||||
this.options
|
||||
),
|
||||
refCount: 0,
|
||||
};
|
||||
|
||||
@@ -13,6 +13,10 @@ import type { PeerStorageOptions } from '../sync/types';
|
||||
import { MANUALLY_STOP } from '../utils/throw-if-aborted';
|
||||
import type { StoreInitOptions, WorkerOps } from './ops';
|
||||
|
||||
export interface StoreConsumerOptions {
|
||||
mergeUpdates?: (updates: Uint8Array[]) => Promise<Uint8Array> | Uint8Array;
|
||||
}
|
||||
|
||||
export class StoreConsumer {
|
||||
private storages: PeerStorageOptions<SpaceStorage> | null = null;
|
||||
private sync: Sync | null = null;
|
||||
@@ -71,7 +75,8 @@ export class StoreConsumer {
|
||||
|
||||
constructor(
|
||||
private readonly availableStorageImplementations: StorageConstructor[],
|
||||
init: StoreInitOptions
|
||||
init: StoreInitOptions,
|
||||
private readonly consumerOptions?: StoreConsumerOptions
|
||||
) {
|
||||
this.initOptions = init;
|
||||
this.initWithOptions(init);
|
||||
@@ -127,7 +132,9 @@ export class StoreConsumer {
|
||||
})
|
||||
),
|
||||
};
|
||||
this.sync = new Sync(this.storages);
|
||||
this.sync = new Sync(this.storages, {
|
||||
mergeUpdates: this.consumerOptions?.mergeUpdates,
|
||||
});
|
||||
this.storages.local.connect();
|
||||
for (const remote of Object.values(this.storages.remotes)) {
|
||||
remote.connect();
|
||||
|
||||
@@ -166,10 +166,6 @@
|
||||
}
|
||||
},
|
||||
"doc": {
|
||||
"experimental.yocto": {
|
||||
"type": "Boolean",
|
||||
"desc": "Use `y-octo` to merge updates at the same time when merging using Yjs."
|
||||
},
|
||||
"history.interval": {
|
||||
"type": "Number",
|
||||
"desc": "The minimum time interval in milliseconds of creating a new history snapshot when doc get updated."
|
||||
|
||||
+45
@@ -132,6 +132,51 @@ class NbStorePlugin : Plugin() {
|
||||
}
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
fun getDocDiff(call: PluginCall) {
|
||||
launch(Dispatchers.IO) {
|
||||
try {
|
||||
val id = call.getStringEnsure("id")
|
||||
val docId = call.getStringEnsure("docId")
|
||||
val state = call.getString("state")
|
||||
val diff = docStoragePool.getDocDiff(universalId = id, docId = docId, state = state)
|
||||
diff?.let {
|
||||
call.resolve(
|
||||
JSObject()
|
||||
.put("docId", it.docId)
|
||||
.put("missing", it.missing)
|
||||
.put("state", it.state)
|
||||
.put("timestamp", it.timestamp)
|
||||
)
|
||||
} ?: call.resolve()
|
||||
} catch (e: Exception) {
|
||||
if (e is UniffiException.Err && e.v1 == "invalid_binary") {
|
||||
call.reject("invalid_binary", null, e)
|
||||
} else {
|
||||
call.reject("Failed to get doc diff, ${e.message}", null, e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
fun mergeUpdates(call: PluginCall) {
|
||||
launch(Dispatchers.IO) {
|
||||
try {
|
||||
val values = call.getArray("updates") ?: throw IllegalArgumentException("updates is required")
|
||||
val updates = (0 until values.length()).map { index -> values.getString(index) }
|
||||
val merged = docStoragePool.mergeUpdates(updates = updates)
|
||||
call.resolve(JSObject().put("bin", merged))
|
||||
} catch (e: Exception) {
|
||||
if (e is UniffiException.Err && e.v1 == "invalid_binary") {
|
||||
call.reject("invalid_binary", null, e)
|
||||
} else {
|
||||
call.reject("Failed to merge updates, ${e.message}", null, e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
fun deleteDoc(call: PluginCall) {
|
||||
launch(Dispatchers.IO) {
|
||||
|
||||
+128
@@ -806,6 +806,10 @@ internal interface UniffiForeignFutureCompleteVoid : com.sun.jna.Callback {
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -860,6 +864,8 @@ fun uniffi_affine_mobile_native_checksum_method_docstoragepool_get_doc_clock(
|
||||
): Short
|
||||
fun uniffi_affine_mobile_native_checksum_method_docstoragepool_get_doc_clocks(
|
||||
): Short
|
||||
fun uniffi_affine_mobile_native_checksum_method_docstoragepool_get_doc_diff(
|
||||
): Short
|
||||
fun uniffi_affine_mobile_native_checksum_method_docstoragepool_get_doc_indexed_clock(
|
||||
): Short
|
||||
fun uniffi_affine_mobile_native_checksum_method_docstoragepool_get_peer_pulled_remote_clock(
|
||||
@@ -896,6 +902,8 @@ fun uniffi_affine_mobile_native_checksum_method_docstoragepool_invalidate_peer_w
|
||||
): Short
|
||||
fun uniffi_affine_mobile_native_checksum_method_docstoragepool_list_blobs(
|
||||
): Short
|
||||
fun uniffi_affine_mobile_native_checksum_method_docstoragepool_merge_updates(
|
||||
): Short
|
||||
fun uniffi_affine_mobile_native_checksum_method_docstoragepool_push_update(
|
||||
): Short
|
||||
fun uniffi_affine_mobile_native_checksum_method_docstoragepool_release_blobs(
|
||||
@@ -995,6 +1003,8 @@ fun uniffi_affine_mobile_native_fn_method_docstoragepool_get_doc_clock(`ptr`: Po
|
||||
): Long
|
||||
fun uniffi_affine_mobile_native_fn_method_docstoragepool_get_doc_clocks(`ptr`: Pointer,`universalId`: RustBuffer.ByValue,`after`: RustBuffer.ByValue,
|
||||
): Long
|
||||
fun uniffi_affine_mobile_native_fn_method_docstoragepool_get_doc_diff(`ptr`: Pointer,`universalId`: RustBuffer.ByValue,`docId`: RustBuffer.ByValue,`state`: RustBuffer.ByValue,
|
||||
): Long
|
||||
fun uniffi_affine_mobile_native_fn_method_docstoragepool_get_doc_indexed_clock(`ptr`: Pointer,`universalId`: RustBuffer.ByValue,`docId`: RustBuffer.ByValue,
|
||||
): Long
|
||||
fun uniffi_affine_mobile_native_fn_method_docstoragepool_get_peer_pulled_remote_clock(`ptr`: Pointer,`universalId`: RustBuffer.ByValue,`peer`: RustBuffer.ByValue,`docId`: RustBuffer.ByValue,
|
||||
@@ -1031,6 +1041,8 @@ fun uniffi_affine_mobile_native_fn_method_docstoragepool_invalidate_peer_workspa
|
||||
): Long
|
||||
fun uniffi_affine_mobile_native_fn_method_docstoragepool_list_blobs(`ptr`: Pointer,`universalId`: RustBuffer.ByValue,
|
||||
): Long
|
||||
fun uniffi_affine_mobile_native_fn_method_docstoragepool_merge_updates(`ptr`: Pointer,`updates`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus,
|
||||
): RustBuffer.ByValue
|
||||
fun uniffi_affine_mobile_native_fn_method_docstoragepool_push_update(`ptr`: Pointer,`universalId`: RustBuffer.ByValue,`docId`: RustBuffer.ByValue,`update`: RustBuffer.ByValue,`createForPeer`: RustBuffer.ByValue,
|
||||
): Long
|
||||
fun uniffi_affine_mobile_native_fn_method_docstoragepool_release_blobs(`ptr`: Pointer,`universalId`: RustBuffer.ByValue,
|
||||
@@ -1236,6 +1248,9 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {
|
||||
if (lib.uniffi_affine_mobile_native_checksum_method_docstoragepool_get_doc_clocks() != 46082.toShort()) {
|
||||
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
|
||||
}
|
||||
if (lib.uniffi_affine_mobile_native_checksum_method_docstoragepool_get_doc_diff() != 22717.toShort()) {
|
||||
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
|
||||
}
|
||||
if (lib.uniffi_affine_mobile_native_checksum_method_docstoragepool_get_doc_indexed_clock() != 17668.toShort()) {
|
||||
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
|
||||
}
|
||||
@@ -1290,6 +1305,9 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {
|
||||
if (lib.uniffi_affine_mobile_native_checksum_method_docstoragepool_list_blobs() != 6777.toShort()) {
|
||||
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
|
||||
}
|
||||
if (lib.uniffi_affine_mobile_native_checksum_method_docstoragepool_merge_updates() != 49313.toShort()) {
|
||||
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
|
||||
}
|
||||
if (lib.uniffi_affine_mobile_native_checksum_method_docstoragepool_push_update() != 60089.toShort()) {
|
||||
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
|
||||
}
|
||||
@@ -1782,6 +1800,8 @@ public interface DocStoragePoolInterface {
|
||||
|
||||
suspend fun `getDocClocks`(`universalId`: kotlin.String, `after`: kotlin.Long?): List<DocClock>
|
||||
|
||||
suspend fun `getDocDiff`(`universalId`: kotlin.String, `docId`: kotlin.String, `state`: kotlin.String?): DocDiff?
|
||||
|
||||
suspend fun `getDocIndexedClock`(`universalId`: kotlin.String, `docId`: kotlin.String): DocIndexedClock?
|
||||
|
||||
suspend fun `getPeerPulledRemoteClock`(`universalId`: kotlin.String, `peer`: kotlin.String, `docId`: kotlin.String): DocClock?
|
||||
@@ -1818,6 +1838,8 @@ public interface DocStoragePoolInterface {
|
||||
|
||||
suspend fun `listBlobs`(`universalId`: kotlin.String): List<ListedBlob>
|
||||
|
||||
fun `mergeUpdates`(`updates`: List<kotlin.String>): kotlin.String
|
||||
|
||||
suspend fun `pushUpdate`(`universalId`: kotlin.String, `docId`: kotlin.String, `update`: kotlin.String, `createForPeer`: kotlin.String?): kotlin.Long
|
||||
|
||||
suspend fun `releaseBlobs`(`universalId`: kotlin.String)
|
||||
@@ -2207,6 +2229,27 @@ open class DocStoragePool: Disposable, AutoCloseable, DocStoragePoolInterface
|
||||
}
|
||||
|
||||
|
||||
@Throws(UniffiException::class)
|
||||
@Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
|
||||
override suspend fun `getDocDiff`(`universalId`: kotlin.String, `docId`: kotlin.String, `state`: kotlin.String?) : DocDiff? {
|
||||
return uniffiRustCallAsync(
|
||||
callWithPointer { thisPtr ->
|
||||
UniffiLib.INSTANCE.uniffi_affine_mobile_native_fn_method_docstoragepool_get_doc_diff(
|
||||
thisPtr,
|
||||
FfiConverterString.lower(`universalId`),FfiConverterString.lower(`docId`),FfiConverterOptionalString.lower(`state`),
|
||||
)
|
||||
},
|
||||
{ future, callback, continuation -> UniffiLib.INSTANCE.ffi_affine_mobile_native_rust_future_poll_rust_buffer(future, callback, continuation) },
|
||||
{ future, continuation -> UniffiLib.INSTANCE.ffi_affine_mobile_native_rust_future_complete_rust_buffer(future, continuation) },
|
||||
{ future -> UniffiLib.INSTANCE.ffi_affine_mobile_native_rust_future_free_rust_buffer(future) },
|
||||
// lift function
|
||||
{ FfiConverterOptionalTypeDocDiff.lift(it) },
|
||||
// Error FFI converter
|
||||
UniffiException.ErrorHandler,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@Throws(UniffiException::class)
|
||||
@Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
|
||||
override suspend fun `getDocIndexedClock`(`universalId`: kotlin.String, `docId`: kotlin.String) : DocIndexedClock? {
|
||||
@@ -2589,6 +2632,19 @@ open class DocStoragePool: Disposable, AutoCloseable, DocStoragePoolInterface
|
||||
}
|
||||
|
||||
|
||||
@Throws(UniffiException::class)override fun `mergeUpdates`(`updates`: List<kotlin.String>): kotlin.String {
|
||||
return FfiConverterString.lift(
|
||||
callWithPointer {
|
||||
uniffiRustCallWithError(UniffiException) { _status ->
|
||||
UniffiLib.INSTANCE.uniffi_affine_mobile_native_fn_method_docstoragepool_merge_updates(
|
||||
it, FfiConverterSequenceString.lower(`updates`),_status)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Throws(UniffiException::class)
|
||||
@Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
|
||||
override suspend fun `pushUpdate`(`universalId`: kotlin.String, `docId`: kotlin.String, `update`: kotlin.String, `createForPeer`: kotlin.String?) : kotlin.Long {
|
||||
@@ -3017,6 +3073,46 @@ public object FfiConverterTypeDocClock: FfiConverterRustBuffer<DocClock> {
|
||||
|
||||
|
||||
|
||||
data class DocDiff (
|
||||
var `docId`: kotlin.String,
|
||||
var `missing`: kotlin.String,
|
||||
var `state`: kotlin.String,
|
||||
var `timestamp`: kotlin.Long
|
||||
) {
|
||||
|
||||
companion object
|
||||
}
|
||||
|
||||
/**
|
||||
* @suppress
|
||||
*/
|
||||
public object FfiConverterTypeDocDiff: FfiConverterRustBuffer<DocDiff> {
|
||||
override fun read(buf: ByteBuffer): DocDiff {
|
||||
return DocDiff(
|
||||
FfiConverterString.read(buf),
|
||||
FfiConverterString.read(buf),
|
||||
FfiConverterString.read(buf),
|
||||
FfiConverterLong.read(buf),
|
||||
)
|
||||
}
|
||||
|
||||
override fun allocationSize(value: DocDiff) = (
|
||||
FfiConverterString.allocationSize(value.`docId`) +
|
||||
FfiConverterString.allocationSize(value.`missing`) +
|
||||
FfiConverterString.allocationSize(value.`state`) +
|
||||
FfiConverterLong.allocationSize(value.`timestamp`)
|
||||
)
|
||||
|
||||
override fun write(value: DocDiff, buf: ByteBuffer) {
|
||||
FfiConverterString.write(value.`docId`, buf)
|
||||
FfiConverterString.write(value.`missing`, buf)
|
||||
FfiConverterString.write(value.`state`, buf)
|
||||
FfiConverterLong.write(value.`timestamp`, buf)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
data class DocIndexedClock (
|
||||
var `docId`: kotlin.String,
|
||||
var `timestamp`: kotlin.Long,
|
||||
@@ -3693,6 +3789,38 @@ public object FfiConverterOptionalTypeDocClock: FfiConverterRustBuffer<DocClock?
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @suppress
|
||||
*/
|
||||
public object FfiConverterOptionalTypeDocDiff: FfiConverterRustBuffer<DocDiff?> {
|
||||
override fun read(buf: ByteBuffer): DocDiff? {
|
||||
if (buf.get().toInt() == 0) {
|
||||
return null
|
||||
}
|
||||
return FfiConverterTypeDocDiff.read(buf)
|
||||
}
|
||||
|
||||
override fun allocationSize(value: DocDiff?): ULong {
|
||||
if (value == null) {
|
||||
return 1UL
|
||||
} else {
|
||||
return 1UL + FfiConverterTypeDocDiff.allocationSize(value)
|
||||
}
|
||||
}
|
||||
|
||||
override fun write(value: DocDiff?, buf: ByteBuffer) {
|
||||
if (value == null) {
|
||||
buf.put(0)
|
||||
} else {
|
||||
buf.put(1)
|
||||
FfiConverterTypeDocDiff.write(value, buf)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @suppress
|
||||
*/
|
||||
|
||||
@@ -42,59 +42,59 @@ version-catalog-update = "1.0.0"
|
||||
webkit = "1.16.0"
|
||||
|
||||
[libraries]
|
||||
android-gradle-plugin = { module = "com.android.tools.build:gradle", version.ref = "android-gradle-plugin" }
|
||||
androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidx-activity-compose" }
|
||||
androidx-appcompat = { module = "androidx.appcompat:appcompat", version.ref = "androidx-appcompat" }
|
||||
androidx-browser = { module = "androidx.browser:browser", version.ref = "androidx-browser" }
|
||||
androidx-compose-bom = { module = "androidx.compose:compose-bom", version.ref = "androidx-compose-bom" }
|
||||
androidx-compose-foundation-layout = { module = "androidx.compose.foundation:foundation-layout" }
|
||||
androidx-compose-material3 = { module = "androidx.compose.material3:material3" }
|
||||
androidx-compose-runtime-livedata = { module = "androidx.compose.runtime:runtime-livedata" }
|
||||
androidx-compose-ui-googlefonts = { module = "androidx.compose.ui:ui-text-google-fonts" }
|
||||
androidx-compose-ui-test-manifest = { module = "androidx.compose.ui:ui-test-manifest" }
|
||||
androidx-compose-ui-tooling = { module = "androidx.compose.ui:ui-tooling" }
|
||||
androidx-compose-ui-tooling-preview = { module = "androidx.compose.ui:ui-tooling-preview" }
|
||||
androidx-compose-ui-util = { module = "androidx.compose.ui:ui-util" }
|
||||
androidx-compose-ui-viewbinding = { module = "androidx.compose.ui:ui-viewbinding" }
|
||||
androidx-coordinatorlayout = { module = "androidx.coordinatorlayout:coordinatorlayout", version.ref = "androidx-coordinatorlayout" }
|
||||
androidx-core-ktx = { module = "androidx.core:core-ktx", version.ref = "androidx-core-ktx" }
|
||||
androidx-core-splashscreen = { module = "androidx.core:core-splashscreen", version.ref = "androidx-core-splashscreen" }
|
||||
androidx-datastore-preferences = { module = "androidx.datastore:datastore-preferences", version.ref = "androidx-datastore-preferences" }
|
||||
androidx-espresso-core = { module = "androidx.test.espresso:espresso-core", version.ref = "androidx-espresso-core" }
|
||||
androidx-junit = { module = "androidx.test.ext:junit", version.ref = "androidx-junit" }
|
||||
androidx-lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "androidx-lifecycle-compose" }
|
||||
androidx-lifecycle-viewModelCompose = { module = "androidx.lifecycle:lifecycle-viewmodel-compose", version.ref = "androidx-lifecycle-compose" }
|
||||
androidx-navigation-compose = { module = "androidx.navigation:navigation-compose", version.ref = "androidx-navigation" }
|
||||
androidx-navigation-fragment = { module = "androidx.navigation:navigation-fragment-ktx", version.ref = "androidx-navigation" }
|
||||
androidx-navigation-ui-ktx = { module = "androidx.navigation:navigation-ui-ktx", version.ref = "androidx-navigation" }
|
||||
androidx-webkit = { module = "androidx.webkit:webkit", version.ref = "webkit" }
|
||||
apollo-adapters-core = { module = "com.apollographql.adapters:apollo-adapters-core", version.ref = "apollo-kotlin-adapters" }
|
||||
apollo-adapters-kotlinx-datetime = { module = "com.apollographql.adapters:apollo-adapters-kotlinx-datetime", version.ref = "apollo-kotlin-adapters" }
|
||||
apollo-api = { module = "com.apollographql.apollo:apollo-api", version.ref = "apollo" }
|
||||
apollo-runtime = { module = "com.apollographql.apollo:apollo-runtime", version.ref = "apollo" }
|
||||
firebase-analytics = { module = "com.google.firebase:firebase-analytics" }
|
||||
firebase-bom = { module = "com.google.firebase:firebase-bom", version.ref = "firebase-bom" }
|
||||
firebase-crashlytics = { module = "com.google.firebase:firebase-crashlytics" }
|
||||
firebase-storage = { module = "com.google.firebase:firebase-storage" }
|
||||
google-services = { module = "com.google.gms:google-services", version.ref = "google-services" }
|
||||
hilt-android-core = { module = "com.google.dagger:hilt-android", version.ref = "hilt" }
|
||||
hilt-android-testing = { module = "com.google.dagger:hilt-android-testing", version.ref = "hilt" }
|
||||
hilt-compiler = { module = "com.google.dagger:hilt-android-compiler", version.ref = "hilt" }
|
||||
hilt-ext-compiler = { module = "androidx.hilt:hilt-compiler", version.ref = "hilt-ext" }
|
||||
hilt-ext-work = { module = "androidx.hilt:hilt-work", version.ref = "hilt-ext" }
|
||||
jna = { module = "net.java.dev.jna:jna", version.ref = "jna" }
|
||||
junit = { module = "junit:junit", version.ref = "junit" }
|
||||
kotlinx-coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "kotlinx-coroutines" }
|
||||
kotlinx-datetime = { module = "org.jetbrains.kotlinx:kotlinx-datetime", version.ref = "kotlinx-datetime" }
|
||||
kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinx-serialization-json" }
|
||||
okhttp = { module = "com.squareup.okhttp3:okhttp" }
|
||||
okhttp-bom = { module = "com.squareup.okhttp3:okhttp-bom", version.ref = "okhttp-bom" }
|
||||
okhttp-coroutines = { module = "com.squareup.okhttp3:okhttp-coroutines" }
|
||||
okhttp-logging = { module = "com.squareup.okhttp3:logging-interceptor" }
|
||||
okhttp-sse = { module = "com.squareup.okhttp3:okhttp-sse" }
|
||||
richtext-commonmark = { module = "com.halilibo.compose-richtext:richtext-commonmark", version.ref = "richtext" }
|
||||
richtext-ui = { module = "com.halilibo.compose-richtext:richtext-ui", version.ref = "richtext" }
|
||||
timber = { module = "com.jakewharton.timber:timber", version.ref = "timber" }
|
||||
android-gradle-plugin = { module = "com.android.tools.build:gradle", version.ref = "android-gradle-plugin" }
|
||||
androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidx-activity-compose" }
|
||||
androidx-appcompat = { module = "androidx.appcompat:appcompat", version.ref = "androidx-appcompat" }
|
||||
androidx-browser = { module = "androidx.browser:browser", version.ref = "androidx-browser" }
|
||||
androidx-compose-bom = { module = "androidx.compose:compose-bom", version.ref = "androidx-compose-bom" }
|
||||
androidx-compose-foundation-layout = { module = "androidx.compose.foundation:foundation-layout" }
|
||||
androidx-compose-material3 = { module = "androidx.compose.material3:material3" }
|
||||
androidx-compose-runtime-livedata = { module = "androidx.compose.runtime:runtime-livedata" }
|
||||
androidx-compose-ui-googlefonts = { module = "androidx.compose.ui:ui-text-google-fonts" }
|
||||
androidx-compose-ui-test-manifest = { module = "androidx.compose.ui:ui-test-manifest" }
|
||||
androidx-compose-ui-tooling = { module = "androidx.compose.ui:ui-tooling" }
|
||||
androidx-compose-ui-tooling-preview = { module = "androidx.compose.ui:ui-tooling-preview" }
|
||||
androidx-compose-ui-util = { module = "androidx.compose.ui:ui-util" }
|
||||
androidx-compose-ui-viewbinding = { module = "androidx.compose.ui:ui-viewbinding" }
|
||||
androidx-coordinatorlayout = { module = "androidx.coordinatorlayout:coordinatorlayout", version.ref = "androidx-coordinatorlayout" }
|
||||
androidx-core-ktx = { module = "androidx.core:core-ktx", version.ref = "androidx-core-ktx" }
|
||||
androidx-core-splashscreen = { module = "androidx.core:core-splashscreen", version.ref = "androidx-core-splashscreen" }
|
||||
androidx-datastore-preferences = { module = "androidx.datastore:datastore-preferences", version.ref = "androidx-datastore-preferences" }
|
||||
androidx-espresso-core = { module = "androidx.test.espresso:espresso-core", version.ref = "androidx-espresso-core" }
|
||||
androidx-junit = { module = "androidx.test.ext:junit", version.ref = "androidx-junit" }
|
||||
androidx-lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "androidx-lifecycle-compose" }
|
||||
androidx-lifecycle-viewModelCompose = { module = "androidx.lifecycle:lifecycle-viewmodel-compose", version.ref = "androidx-lifecycle-compose" }
|
||||
androidx-navigation-compose = { module = "androidx.navigation:navigation-compose", version.ref = "androidx-navigation" }
|
||||
androidx-navigation-fragment = { module = "androidx.navigation:navigation-fragment-ktx", version.ref = "androidx-navigation" }
|
||||
androidx-navigation-ui-ktx = { module = "androidx.navigation:navigation-ui-ktx", version.ref = "androidx-navigation" }
|
||||
androidx-webkit = { module = "androidx.webkit:webkit", version.ref = "webkit" }
|
||||
apollo-adapters-core = { module = "com.apollographql.adapters:apollo-adapters-core", version.ref = "apollo-kotlin-adapters" }
|
||||
apollo-adapters-kotlinx-datetime = { module = "com.apollographql.adapters:apollo-adapters-kotlinx-datetime", version.ref = "apollo-kotlin-adapters" }
|
||||
apollo-api = { module = "com.apollographql.apollo:apollo-api", version.ref = "apollo" }
|
||||
apollo-runtime = { module = "com.apollographql.apollo:apollo-runtime", version.ref = "apollo" }
|
||||
firebase-analytics = { module = "com.google.firebase:firebase-analytics" }
|
||||
firebase-bom = { module = "com.google.firebase:firebase-bom", version.ref = "firebase-bom" }
|
||||
firebase-crashlytics = { module = "com.google.firebase:firebase-crashlytics" }
|
||||
firebase-storage = { module = "com.google.firebase:firebase-storage" }
|
||||
google-services = { module = "com.google.gms:google-services", version.ref = "google-services" }
|
||||
hilt-android-core = { module = "com.google.dagger:hilt-android", version.ref = "hilt" }
|
||||
hilt-android-testing = { module = "com.google.dagger:hilt-android-testing", version.ref = "hilt" }
|
||||
hilt-compiler = { module = "com.google.dagger:hilt-android-compiler", version.ref = "hilt" }
|
||||
hilt-ext-compiler = { module = "androidx.hilt:hilt-compiler", version.ref = "hilt-ext" }
|
||||
hilt-ext-work = { module = "androidx.hilt:hilt-work", version.ref = "hilt-ext" }
|
||||
jna = { module = "net.java.dev.jna:jna", version.ref = "jna" }
|
||||
junit = { module = "junit:junit", version.ref = "junit" }
|
||||
kotlinx-coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "kotlinx-coroutines" }
|
||||
kotlinx-datetime = { module = "org.jetbrains.kotlinx:kotlinx-datetime", version.ref = "kotlinx-datetime" }
|
||||
kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinx-serialization-json" }
|
||||
okhttp = { module = "com.squareup.okhttp3:okhttp" }
|
||||
okhttp-bom = { module = "com.squareup.okhttp3:okhttp-bom", version.ref = "okhttp-bom" }
|
||||
okhttp-coroutines = { module = "com.squareup.okhttp3:okhttp-coroutines" }
|
||||
okhttp-logging = { module = "com.squareup.okhttp3:logging-interceptor" }
|
||||
okhttp-sse = { module = "com.squareup.okhttp3:okhttp-sse" }
|
||||
richtext-commonmark = { module = "com.halilibo.compose-richtext:richtext-commonmark", version.ref = "richtext" }
|
||||
richtext-ui = { module = "com.halilibo.compose-richtext:richtext-ui", version.ref = "richtext" }
|
||||
timber = { module = "com.jakewharton.timber:timber", version.ref = "timber" }
|
||||
|
||||
[plugins]
|
||||
android-application = { id = "com.android.application", version.ref = "android-gradle-plugin" }
|
||||
|
||||
@@ -522,5 +522,11 @@ function createStoreManagerClient() {
|
||||
{ type: 'auth-access-token-channel', port: authTokenChannelClient },
|
||||
[authTokenChannelClient]
|
||||
);
|
||||
return new StoreManagerClient(new OpClient(worker));
|
||||
const nativeMergeUpdates = NbStoreNativeDBApis.mergeUpdates;
|
||||
return new StoreManagerClient(new OpClient(worker), {
|
||||
mergeUpdates: nativeMergeUpdates
|
||||
? updates =>
|
||||
updates.length === 1 ? updates[0] : nativeMergeUpdates(updates)
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
import { idbStoragesIndexerOnly } from '@affine/nbstore/idb';
|
||||
import {
|
||||
bindNativeDBApis,
|
||||
getNativeMergeUpdates,
|
||||
type NativeDBApis,
|
||||
sqliteStorages,
|
||||
} from '@affine/nbstore/sqlite';
|
||||
@@ -66,11 +67,25 @@ const consumer = new OpConsumer<WorkerManagerOps>(
|
||||
globalThis as MessageCommunicapable
|
||||
);
|
||||
|
||||
const storeManager = new StoreManagerConsumer([
|
||||
...idbStoragesIndexerOnly,
|
||||
...sqliteStorages,
|
||||
...broadcastChannelStorages,
|
||||
...cloudStorages,
|
||||
]);
|
||||
const storeManager = new StoreManagerConsumer(
|
||||
[
|
||||
...idbStoragesIndexerOnly,
|
||||
...sqliteStorages,
|
||||
...broadcastChannelStorages,
|
||||
...cloudStorages,
|
||||
],
|
||||
{
|
||||
mergeUpdates: updates => {
|
||||
if (updates.length === 1) {
|
||||
return updates[0];
|
||||
}
|
||||
const nativeMerge = getNativeMergeUpdates();
|
||||
if (!nativeMerge) {
|
||||
throw new Error('Native mergeUpdates is not bound');
|
||||
}
|
||||
return nativeMerge(updates);
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
storeManager.bindConsumer(consumer);
|
||||
@@ -67,6 +67,15 @@ export interface NbStorePlugin {
|
||||
id: string;
|
||||
docId: string;
|
||||
}) => Promise<{ docId: string; bin: string; timestamp: number } | undefined>;
|
||||
getDocDiff: (options: {
|
||||
id: string;
|
||||
docId: string;
|
||||
state?: string;
|
||||
}) => Promise<
|
||||
| { docId: string; missing: string; state: string; timestamp: number }
|
||||
| undefined
|
||||
>;
|
||||
mergeUpdates: (options: { updates: string[] }) => Promise<{ bin: string }>;
|
||||
deleteDoc: (options: { id: string; docId: string }) => Promise<void>;
|
||||
getDocClocks: (options: { id: string; after?: number | null }) => Promise<{
|
||||
clocks: {
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
type BlobRecord,
|
||||
type CrawlResult,
|
||||
type DocClock,
|
||||
type DocDiff,
|
||||
type DocIndexedClock,
|
||||
type DocRecord,
|
||||
type ListedBlobRecord,
|
||||
@@ -60,6 +61,32 @@ export const NbStoreNativeDBApis: NativeDBApis = {
|
||||
}
|
||||
: null;
|
||||
},
|
||||
getDocDiff: async function (
|
||||
id: string,
|
||||
docId: string,
|
||||
state?: Uint8Array
|
||||
): Promise<DocDiff | null> {
|
||||
const diff = await NbStore.getDocDiff({
|
||||
id,
|
||||
docId,
|
||||
state: state ? await uint8ArrayToBase64(state) : undefined,
|
||||
});
|
||||
return diff
|
||||
? {
|
||||
docId: diff.docId,
|
||||
missing: base64ToUint8Array(diff.missing),
|
||||
state: base64ToUint8Array(diff.state),
|
||||
timestamp: new Date(diff.timestamp),
|
||||
}
|
||||
: null;
|
||||
},
|
||||
mergeUpdates: async function (updates: Uint8Array[]): Promise<Uint8Array> {
|
||||
const encoded = await Promise.all(
|
||||
updates.map(update => uint8ArrayToBase64(update))
|
||||
);
|
||||
const { bin } = await NbStore.mergeUpdates({ updates: encoded });
|
||||
return base64ToUint8Array(bin);
|
||||
},
|
||||
deleteDoc: async function (id: string, docId: string): Promise<void> {
|
||||
await NbStore.deleteDoc({
|
||||
id,
|
||||
|
||||
@@ -37,7 +37,14 @@ function createStoreManagerClient() {
|
||||
console.error('failed to connect worker', err);
|
||||
});
|
||||
|
||||
const storeManager = new StoreManagerClient(new OpClient(portForOpClient));
|
||||
// oxlint-disable-next-line no-non-null-assertion
|
||||
const nativeMergeUpdates = apis!.nbstore.mergeUpdates;
|
||||
const storeManager = new StoreManagerClient(new OpClient(portForOpClient), {
|
||||
mergeUpdates: nativeMergeUpdates
|
||||
? updates =>
|
||||
updates.length === 1 ? updates[0] : nativeMergeUpdates(updates)
|
||||
: undefined,
|
||||
});
|
||||
portForOpClient.start();
|
||||
return storeManager;
|
||||
}
|
||||
|
||||
@@ -7,7 +7,11 @@ import {
|
||||
configureSocketAuthMethod,
|
||||
} from '@affine/nbstore/cloud';
|
||||
import { bindDiskSyncApis, diskStorages } from '@affine/nbstore/disk';
|
||||
import { bindNativeDBApis, sqliteStorages } from '@affine/nbstore/sqlite';
|
||||
import {
|
||||
bindNativeDBApis,
|
||||
getNativeMergeUpdates,
|
||||
sqliteStorages,
|
||||
} from '@affine/nbstore/sqlite';
|
||||
import {
|
||||
bindNativeDBV1Apis,
|
||||
sqliteV1Storages,
|
||||
@@ -36,13 +40,23 @@ configureSocketAuthMethod((endpoint, cb) => {
|
||||
.catch(() => cb({ error: 'AUTH_SESSION_TEMPORARILY_UNAVAILABLE' }));
|
||||
});
|
||||
|
||||
const storeManager = new StoreManagerConsumer([
|
||||
...sqliteStorages,
|
||||
...sqliteV1Storages,
|
||||
...diskStorages,
|
||||
...broadcastChannelStorages,
|
||||
...cloudStorages,
|
||||
]);
|
||||
const nativeMergeUpdates = getNativeMergeUpdates();
|
||||
|
||||
const storeManager = new StoreManagerConsumer(
|
||||
[
|
||||
...sqliteStorages,
|
||||
...sqliteV1Storages,
|
||||
...diskStorages,
|
||||
...broadcastChannelStorages,
|
||||
...cloudStorages,
|
||||
],
|
||||
{
|
||||
mergeUpdates: nativeMergeUpdates
|
||||
? updates =>
|
||||
updates.length === 1 ? updates[0] : nativeMergeUpdates(updates)
|
||||
: undefined,
|
||||
}
|
||||
);
|
||||
|
||||
window.addEventListener('message', ev => {
|
||||
if (ev.data.type === 'electron:worker-connect') {
|
||||
|
||||
@@ -77,14 +77,14 @@
|
||||
"typescript": "npm:@typescript/typescript6@6.0.2",
|
||||
"uuid": "^14.0.0",
|
||||
"vitest": "^4.1.11",
|
||||
"yjs": "^13.6.27",
|
||||
"zod": "^3.25.76"
|
||||
},
|
||||
"dependencies": {
|
||||
"async-call-rpc": "^6.4.2",
|
||||
"electron-updater": "^6.8.9",
|
||||
"link-preview-js": "^4.0.4",
|
||||
"set-cookie-parser": "^2.7.1",
|
||||
"yjs": "^13.6.27"
|
||||
"set-cookie-parser": "^2.7.1"
|
||||
},
|
||||
"build": {
|
||||
"protocols": [
|
||||
|
||||
@@ -87,7 +87,7 @@ export const config = (): BuildOptions => {
|
||||
bundle: true,
|
||||
target: `node${NODE_MAJOR_VERSION}`,
|
||||
platform: 'node',
|
||||
external: ['electron', 'electron-updater', 'yjs', 'semver'],
|
||||
external: ['electron', 'electron-updater', 'semver'],
|
||||
format: 'cjs',
|
||||
loader: {
|
||||
'.node': 'copy',
|
||||
|
||||
@@ -28,6 +28,8 @@ export const nbstoreHandlers: NativeDBApis = {
|
||||
installPeerWorkspaceState: POOL.installPeerWorkspaceState.bind(POOL),
|
||||
confirmPeerDocCreate: POOL.confirmPeerDocCreate.bind(POOL),
|
||||
getDoc: POOL.getDoc.bind(POOL),
|
||||
getDocDiff: POOL.getDocDiff.bind(POOL),
|
||||
mergeUpdates: async (updates: Uint8Array[]) => POOL.mergeUpdates(updates),
|
||||
deleteDoc: POOL.deleteDoc.bind(POOL),
|
||||
getDocClocks: POOL.getDocClocks.bind(POOL),
|
||||
getDocClock: POOL.getDocClock.bind(POOL),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { applyUpdate, Doc as YDoc, encodeStateAsUpdate, transact } from 'yjs';
|
||||
import { compactDocUpdatesV1 } from '@affine/native';
|
||||
|
||||
export function mergeUpdate(updates: Uint8Array[]) {
|
||||
if (updates.length === 0) {
|
||||
@@ -7,11 +7,5 @@ export function mergeUpdate(updates: Uint8Array[]) {
|
||||
if (updates.length === 1) {
|
||||
return updates[0];
|
||||
}
|
||||
const yDoc = new YDoc();
|
||||
transact(yDoc, () => {
|
||||
for (const update of updates) {
|
||||
applyUpdate(yDoc, update);
|
||||
}
|
||||
});
|
||||
return encodeStateAsUpdate(yDoc);
|
||||
return compactDocUpdatesV1(updates);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { parseWorkspaceRootDocMeta } from '@affine/native';
|
||||
import type { SpaceType } from '@affine/nbstore';
|
||||
import { AsyncLock } from '@toeverything/infra/utils';
|
||||
import { Subject } from 'rxjs';
|
||||
import { applyUpdate, Doc as YDoc } from 'yjs';
|
||||
|
||||
import { logger } from '../../logger';
|
||||
import { getWorkspaceMeta } from '../../workspace/meta';
|
||||
@@ -41,18 +41,10 @@ export class WorkspaceSQLiteDB implements AsyncDisposable {
|
||||
};
|
||||
|
||||
getWorkspaceMeta = async () => {
|
||||
const ydoc = new YDoc();
|
||||
const updates = await this.adapter.getUpdates();
|
||||
updates.forEach(update => {
|
||||
applyUpdate(ydoc, update.data);
|
||||
});
|
||||
logger.log(
|
||||
`ydoc.getMap('meta').get('name')`,
|
||||
ydoc.getMap('meta').get('name'),
|
||||
this.path,
|
||||
updates.length
|
||||
);
|
||||
return ydoc.getMap('meta').toJSON();
|
||||
const meta = parseWorkspaceRootDocMeta(updates.map(update => update.data));
|
||||
logger.log('workspace meta name', meta.name, this.path, updates.length);
|
||||
return meta;
|
||||
};
|
||||
|
||||
getWorkspaceName = async () => {
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import path from 'node:path';
|
||||
|
||||
import { DocStorage, ValidationResult } from '@affine/native';
|
||||
import {
|
||||
DocStorage,
|
||||
parseWorkspaceRootDocMeta,
|
||||
ValidationResult,
|
||||
} from '@affine/native';
|
||||
import { parseUniversalId } from '@affine/nbstore';
|
||||
import fs from 'fs-extra';
|
||||
import { nanoid } from 'nanoid';
|
||||
import { applyUpdate, Doc as YDoc } from 'yjs';
|
||||
|
||||
import {
|
||||
normalizeWorkspaceIdForPath,
|
||||
@@ -155,15 +158,18 @@ async function getWorkspaceDocMetaV1(
|
||||
await db.init();
|
||||
await db.checkpoint();
|
||||
const meta = await db.getWorkspaceMeta();
|
||||
if (meta.pageCount == null) {
|
||||
return null;
|
||||
}
|
||||
const dbFileSize = await fs.stat(dbPath);
|
||||
return {
|
||||
id: workspaceId,
|
||||
name: meta.name,
|
||||
avatar: await db.getBlob(meta.avatar),
|
||||
name: meta.name ?? '',
|
||||
avatar: meta.avatar ? await db.getBlob(meta.avatar) : null,
|
||||
fileSize: dbFileSize.size,
|
||||
updatedAt: dbFileSize.mtime,
|
||||
createdAt: dbFileSize.birthtime,
|
||||
docCount: meta.pages.length,
|
||||
docCount: meta.pageCount,
|
||||
dbPath,
|
||||
};
|
||||
} catch {
|
||||
@@ -181,26 +187,25 @@ async function getWorkspaceDocMeta(
|
||||
const { snapshot, updates: pendingUpdates } =
|
||||
await pool.readDocRecordsReadonly(dbPath, workspaceId);
|
||||
if (snapshot || pendingUpdates.length) {
|
||||
const ydoc = new YDoc();
|
||||
if (snapshot) {
|
||||
applyUpdate(ydoc, snapshot.bin);
|
||||
const meta = parseWorkspaceRootDocMeta([
|
||||
...(snapshot ? [snapshot.bin] : []),
|
||||
...pendingUpdates.map(update => update.bin),
|
||||
]);
|
||||
if (meta.pageCount == null) {
|
||||
throw new Error('Missing workspace pages metadata');
|
||||
}
|
||||
pendingUpdates.forEach(update => {
|
||||
applyUpdate(ydoc, update.bin);
|
||||
});
|
||||
const meta = ydoc.getMap('meta').toJSON();
|
||||
const dbFileStat = await fs.stat(dbPath);
|
||||
const blob = meta.avatar
|
||||
? await pool.readBlobReadonly(dbPath, meta.avatar)
|
||||
: null;
|
||||
return {
|
||||
id: workspaceId,
|
||||
name: meta.name,
|
||||
name: meta.name ?? '',
|
||||
avatar: blob ? blob.data : null,
|
||||
fileSize: dbFileStat.size,
|
||||
updatedAt: dbFileStat.mtime,
|
||||
createdAt: dbFileStat.birthtime,
|
||||
docCount: meta.pages.length,
|
||||
docCount: meta.pageCount,
|
||||
dbPath,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -4,7 +4,56 @@ import { universalId } from '@affine/nbstore';
|
||||
import fs from 'fs-extra';
|
||||
import { v4 } from 'uuid';
|
||||
import { afterAll, afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { Doc as YDoc, encodeStateAsUpdate, encodeStateVector } from 'yjs';
|
||||
import {
|
||||
applyUpdate,
|
||||
Array as YArray,
|
||||
Doc as YDoc,
|
||||
encodeStateAsUpdate,
|
||||
encodeStateVector,
|
||||
} from 'yjs';
|
||||
|
||||
function encodeVarUint(value: number): number[] {
|
||||
const out: number[] = [];
|
||||
let n = value >>> 0;
|
||||
while (n > 0x7f) {
|
||||
out.push(0x80 | (n & 0x7f));
|
||||
n >>>= 7;
|
||||
}
|
||||
out.push(n & 0x7f);
|
||||
return out;
|
||||
}
|
||||
|
||||
function encodeVarString(value: string): number[] {
|
||||
const bytes = Buffer.from(value, 'utf8');
|
||||
return [...encodeVarUint(bytes.length), ...bytes];
|
||||
}
|
||||
|
||||
function encodeLegacyContentJsonMeta(
|
||||
entries: ReadonlyArray<[string, string]>
|
||||
): Uint8Array {
|
||||
const out: number[] = [];
|
||||
// 1 client
|
||||
out.push(...encodeVarUint(1));
|
||||
// N structs for client 1 starting at clock 0
|
||||
out.push(...encodeVarUint(entries.length));
|
||||
out.push(...encodeVarUint(1));
|
||||
out.push(...encodeVarUint(0));
|
||||
|
||||
for (const [key, jsonElem] of entries) {
|
||||
// info = ITEM_HAS_PARENT_SUB (0x20) | Content::Json (2)
|
||||
out.push(0x20 | 2);
|
||||
// named root
|
||||
out.push(1);
|
||||
out.push(...encodeVarString('meta'));
|
||||
out.push(...encodeVarString(key));
|
||||
out.push(...encodeVarUint(1));
|
||||
out.push(...encodeVarString(jsonElem));
|
||||
}
|
||||
|
||||
// Empty delete set
|
||||
out.push(...encodeVarUint(0));
|
||||
return new Uint8Array(out);
|
||||
}
|
||||
|
||||
const tmpDir = path.join(__dirname, 'tmp');
|
||||
const appDataPath = path.join(tmpDir, 'app-data');
|
||||
@@ -77,6 +126,195 @@ describe('workspace db management', () => {
|
||||
await pool.disconnect(workspaceId);
|
||||
});
|
||||
|
||||
test('deleted workspace metadata reads Y.Array pages and avatar blob', async () => {
|
||||
const { getDeletedWorkspaces } =
|
||||
await import('@affine/electron/helper/workspace/handlers');
|
||||
const { getDocStoragePool } =
|
||||
await import('@affine/electron/helper/nbstore');
|
||||
const workspaceId = v4();
|
||||
const dbPath = path.join(
|
||||
appDataPath,
|
||||
'deleted-workspaces',
|
||||
workspaceId,
|
||||
'storage.db'
|
||||
);
|
||||
await fs.ensureDir(path.dirname(dbPath));
|
||||
const pool = getDocStoragePool();
|
||||
await pool.connect(workspaceId, dbPath);
|
||||
|
||||
const avatarKey = 'avatar-blob-key';
|
||||
const avatarBytes = new Uint8Array([1, 2, 3, 4]);
|
||||
await pool.setBlob(workspaceId, {
|
||||
key: avatarKey,
|
||||
data: avatarBytes,
|
||||
mime: 'image/png',
|
||||
});
|
||||
|
||||
const root = new YDoc();
|
||||
const meta = root.getMap('meta');
|
||||
meta.set('name', 'Workspace With YArray');
|
||||
meta.set('avatar', avatarKey);
|
||||
const pages = new YArray();
|
||||
pages.push([{ id: 'page-1' }, { id: 'page-2' }]);
|
||||
meta.set('pages', pages);
|
||||
await pool.pushUpdate(workspaceId, workspaceId, encodeStateAsUpdate(root));
|
||||
|
||||
const deleted = await getDeletedWorkspaces();
|
||||
const entry = deleted.items.find(item => item.id === workspaceId);
|
||||
expect(entry).toMatchObject({
|
||||
name: 'Workspace With YArray',
|
||||
docCount: 2,
|
||||
});
|
||||
expect(entry?.avatar).toEqual(avatarBytes);
|
||||
await pool.disconnect(workspaceId);
|
||||
});
|
||||
|
||||
test('legacy V1 ContentJSON root meta matches Yjs in getDeletedWorkspaces and WorkspaceSQLiteDB', async () => {
|
||||
const { getDeletedWorkspaces } =
|
||||
await import('@affine/electron/helper/workspace/handlers');
|
||||
const { getDocStoragePool } =
|
||||
await import('@affine/electron/helper/nbstore');
|
||||
const { WorkspaceSQLiteDB } =
|
||||
await import('@affine/electron/helper/nbstore/v1/workspace-db-adapter');
|
||||
|
||||
const legacyUpdate = encodeLegacyContentJsonMeta([
|
||||
['name', '"Test"'],
|
||||
['avatar', '"img"'],
|
||||
['pages', '[{"id":"1"},{"id":"2"}]'],
|
||||
]);
|
||||
|
||||
// Ground truth from Yjs
|
||||
const ydoc = new YDoc();
|
||||
applyUpdate(ydoc, legacyUpdate);
|
||||
const yjsMeta = ydoc.getMap('meta').toJSON() as {
|
||||
name: string;
|
||||
avatar: string;
|
||||
pages: unknown[];
|
||||
};
|
||||
expect(yjsMeta.name).toBe('Test');
|
||||
expect(yjsMeta.avatar).toBe('img');
|
||||
expect(yjsMeta.pages).toHaveLength(2);
|
||||
|
||||
// 1. nbstore getDeletedWorkspaces
|
||||
const workspaceId = v4();
|
||||
const dbPath = path.join(
|
||||
appDataPath,
|
||||
'deleted-workspaces',
|
||||
workspaceId,
|
||||
'storage.db'
|
||||
);
|
||||
await fs.ensureDir(path.dirname(dbPath));
|
||||
const pool = getDocStoragePool();
|
||||
await pool.connect(workspaceId, dbPath);
|
||||
await pool.pushUpdate(workspaceId, workspaceId, legacyUpdate);
|
||||
|
||||
const deleted = await getDeletedWorkspaces();
|
||||
expect(deleted.items.find(item => item.id === workspaceId)).toMatchObject({
|
||||
name: yjsMeta.name,
|
||||
docCount: yjsMeta.pages.length,
|
||||
});
|
||||
await pool.disconnect(workspaceId);
|
||||
|
||||
// 2. Legacy V1 WorkspaceSQLiteDB
|
||||
const v1DbPath = path.join(tmpDir, 'v1-legacy-meta.db');
|
||||
await fs.ensureDir(path.dirname(v1DbPath));
|
||||
await using v1Db = new WorkspaceSQLiteDB(v1DbPath, workspaceId);
|
||||
await v1Db.init();
|
||||
await v1Db.addUpdateToSQLite(legacyUpdate, workspaceId);
|
||||
const v1Meta = await v1Db.getWorkspaceMeta();
|
||||
expect(v1Meta).toEqual({
|
||||
name: yjsMeta.name,
|
||||
avatar: yjsMeta.avatar,
|
||||
pageCount: yjsMeta.pages.length,
|
||||
});
|
||||
});
|
||||
|
||||
test('WorkspaceSQLiteDB tryTrim compacts deleted 4x64KiB payloads and preserves pending out-of-order updates', async () => {
|
||||
const { WorkspaceSQLiteDB } =
|
||||
await import('@affine/electron/helper/nbstore/v1/workspace-db-adapter');
|
||||
|
||||
// 1. 4x64KiB insert + delete compacted on tryTrim
|
||||
const gcDbPath = path.join(tmpDir, 'v1-gc-trim.db');
|
||||
const gcWorkspaceId = v4();
|
||||
await fs.ensureDir(path.dirname(gcDbPath));
|
||||
|
||||
const gcDoc = new YDoc();
|
||||
gcDoc.clientID = 17;
|
||||
const gcText = gcDoc.getText('body');
|
||||
const chunk = 'x'.repeat(64 * 1024);
|
||||
const gcUpdates: Uint8Array[] = [];
|
||||
let sv = encodeStateVector(gcDoc);
|
||||
for (let i = 0; i < 4; i++) {
|
||||
gcText.insert(0, chunk);
|
||||
gcUpdates.push(encodeStateAsUpdate(gcDoc, sv));
|
||||
sv = encodeStateVector(gcDoc);
|
||||
|
||||
gcText.delete(0, chunk.length);
|
||||
gcUpdates.push(encodeStateAsUpdate(gcDoc, sv));
|
||||
sv = encodeStateVector(gcDoc);
|
||||
}
|
||||
|
||||
{
|
||||
await using db = new WorkspaceSQLiteDB(gcDbPath, gcWorkspaceId);
|
||||
await db.init();
|
||||
await db.adapter.addUpdateToSQLite(
|
||||
gcUpdates.map(data => ({ data, docId: undefined }))
|
||||
);
|
||||
}
|
||||
|
||||
// Reopening calls init() -> tryTrim() which compacts and writes back to SQLite.
|
||||
{
|
||||
await using reopened = new WorkspaceSQLiteDB(gcDbPath, gcWorkspaceId);
|
||||
await reopened.init();
|
||||
const rows = await reopened.adapter.getUpdates();
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0].data.byteLength).toBeLessThan(64);
|
||||
|
||||
const verifyDoc = new YDoc();
|
||||
applyUpdate(verifyDoc, rows[0].data);
|
||||
expect(verifyDoc.getText('body').toString()).toBe('');
|
||||
}
|
||||
|
||||
// 2. Out-of-order update with missing prior dependency preserved across compaction
|
||||
const pendingDbPath = path.join(tmpDir, 'v1-pending-trim.db');
|
||||
const pendingWorkspaceId = v4();
|
||||
const author = new YDoc();
|
||||
author.clientID = 21;
|
||||
const authorText = author.getText('body');
|
||||
authorText.insert(0, 'hello');
|
||||
const u1 = encodeStateAsUpdate(author);
|
||||
const sv1 = encodeStateVector(author);
|
||||
authorText.insert(5, ' world');
|
||||
const u2 = encodeStateAsUpdate(author, sv1);
|
||||
const sv2 = encodeStateVector(author);
|
||||
authorText.insert(11, '!');
|
||||
const u3 = encodeStateAsUpdate(author, sv2);
|
||||
|
||||
{
|
||||
await using db = new WorkspaceSQLiteDB(pendingDbPath, pendingWorkspaceId);
|
||||
await db.init();
|
||||
// Insert u2 and u3 without u1 so tryTrim compacts an incomplete stream.
|
||||
await db.adapter.addUpdateToSQLite([
|
||||
{ data: u2, docId: undefined },
|
||||
{ data: u3, docId: undefined },
|
||||
]);
|
||||
}
|
||||
|
||||
// Reopen triggers tryTrim() on incomplete stream (u2 + u3), then add missing u1.
|
||||
{
|
||||
await using reopened = new WorkspaceSQLiteDB(
|
||||
pendingDbPath,
|
||||
pendingWorkspaceId
|
||||
);
|
||||
await reopened.init();
|
||||
await reopened.addUpdateToSQLite(u1, pendingWorkspaceId);
|
||||
const merged = await reopened.getDocAsUpdates(pendingWorkspaceId);
|
||||
const verifyDoc = new YDoc();
|
||||
applyUpdate(verifyDoc, merged);
|
||||
expect(verifyDoc.getText('body').toString()).toBe('hello world!');
|
||||
}
|
||||
});
|
||||
|
||||
test('list local workspace ids', async () => {
|
||||
const { listLocalWorkspaceIds } =
|
||||
await import('@affine/electron/helper/workspace/handlers');
|
||||
|
||||
@@ -13,6 +13,8 @@ public class NbStorePlugin: CAPPlugin, CAPBridgedPlugin {
|
||||
CAPPluginMethod(name: "setSpaceId", returnType: CAPPluginReturnPromise),
|
||||
CAPPluginMethod(name: "pushUpdate", returnType: CAPPluginReturnPromise),
|
||||
CAPPluginMethod(name: "getDoc", returnType: CAPPluginReturnPromise),
|
||||
CAPPluginMethod(name: "getDocDiff", returnType: CAPPluginReturnPromise),
|
||||
CAPPluginMethod(name: "mergeUpdates", returnType: CAPPluginReturnPromise),
|
||||
CAPPluginMethod(name: "deleteDoc", returnType: CAPPluginReturnPromise),
|
||||
CAPPluginMethod(name: "getDocClocks", returnType: CAPPluginReturnPromise),
|
||||
CAPPluginMethod(name: "getDocClock", returnType: CAPPluginReturnPromise),
|
||||
@@ -140,6 +142,44 @@ public class NbStorePlugin: CAPPlugin, CAPBridgedPlugin {
|
||||
}
|
||||
}
|
||||
|
||||
@objc func getDocDiff(_ call: CAPPluginCall) {
|
||||
Task {
|
||||
do {
|
||||
let id = try call.getStringEnsure("id")
|
||||
let docId = try call.getStringEnsure("docId")
|
||||
let state = call.getString("state")
|
||||
if let diff = try await docStoragePool.getDocDiff(universalId: id, docId: docId, state: state) {
|
||||
call.resolve([
|
||||
"docId": diff.docId,
|
||||
"missing": diff.missing,
|
||||
"state": diff.state,
|
||||
"timestamp": diff.timestamp,
|
||||
])
|
||||
} else {
|
||||
call.resolve()
|
||||
}
|
||||
} catch UniffiError.Err(let message) where message == "invalid_binary" {
|
||||
call.reject("invalid_binary")
|
||||
} catch {
|
||||
call.reject("Failed to get doc diff, \(error)", nil, error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc func mergeUpdates(_ call: CAPPluginCall) {
|
||||
Task {
|
||||
do {
|
||||
let updates = try call.getArrayEnsure("updates", String.self)
|
||||
let merged = try docStoragePool.mergeUpdates(updates: updates)
|
||||
call.resolve(["bin": merged])
|
||||
} catch UniffiError.Err(let message) where message == "invalid_binary" {
|
||||
call.reject("invalid_binary")
|
||||
} catch {
|
||||
call.reject("Failed to merge updates, \(error)", nil, error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc func deleteDoc(_ call: CAPPluginCall) {
|
||||
Task {
|
||||
do {
|
||||
|
||||
@@ -544,6 +544,8 @@ public protocol DocStoragePoolProtocol: AnyObject, Sendable {
|
||||
|
||||
func getDocClocks(universalId: String, after: Int64?) async throws -> [DocClock]
|
||||
|
||||
func getDocDiff(universalId: String, docId: String, state: String?) async throws -> DocDiff?
|
||||
|
||||
func getDocIndexedClock(universalId: String, docId: String) async throws -> DocIndexedClock?
|
||||
|
||||
func getPeerPulledRemoteClock(universalId: String, peer: String, docId: String) async throws -> DocClock?
|
||||
@@ -580,6 +582,8 @@ public protocol DocStoragePoolProtocol: AnyObject, Sendable {
|
||||
|
||||
func listBlobs(universalId: String) async throws -> [ListedBlob]
|
||||
|
||||
func mergeUpdates(updates: [String]) throws -> String
|
||||
|
||||
func pushUpdate(universalId: String, docId: String, update: String, createForPeer: String?) async throws -> Int64
|
||||
|
||||
func releaseBlobs(universalId: String) async throws
|
||||
@@ -877,6 +881,23 @@ open func getDocClocks(universalId: String, after: Int64?)async throws -> [DocC
|
||||
)
|
||||
}
|
||||
|
||||
open func getDocDiff(universalId: String, docId: String, state: String?)async throws -> DocDiff? {
|
||||
return
|
||||
try await uniffiRustCallAsync(
|
||||
rustFutureFunc: {
|
||||
uniffi_affine_mobile_native_fn_method_docstoragepool_get_doc_diff(
|
||||
self.uniffiClonePointer(),
|
||||
FfiConverterString.lower(universalId),FfiConverterString.lower(docId),FfiConverterOptionString.lower(state)
|
||||
)
|
||||
},
|
||||
pollFunc: ffi_affine_mobile_native_rust_future_poll_rust_buffer,
|
||||
completeFunc: ffi_affine_mobile_native_rust_future_complete_rust_buffer,
|
||||
freeFunc: ffi_affine_mobile_native_rust_future_free_rust_buffer,
|
||||
liftFunc: FfiConverterOptionTypeDocDiff.lift,
|
||||
errorHandler: FfiConverterTypeUniffiError_lift
|
||||
)
|
||||
}
|
||||
|
||||
open func getDocIndexedClock(universalId: String, docId: String)async throws -> DocIndexedClock? {
|
||||
return
|
||||
try await uniffiRustCallAsync(
|
||||
@@ -1183,6 +1204,14 @@ open func listBlobs(universalId: String)async throws -> [ListedBlob] {
|
||||
)
|
||||
}
|
||||
|
||||
open func mergeUpdates(updates: [String])throws -> String {
|
||||
return try FfiConverterString.lift(try rustCallWithError(FfiConverterTypeUniffiError_lift) {
|
||||
uniffi_affine_mobile_native_fn_method_docstoragepool_merge_updates(self.uniffiClonePointer(),
|
||||
FfiConverterSequenceString.lower(updates),$0
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
open func pushUpdate(universalId: String, docId: String, update: String, createForPeer: String?)async throws -> Int64 {
|
||||
return
|
||||
try await uniffiRustCallAsync(
|
||||
@@ -1777,6 +1806,92 @@ public func FfiConverterTypeDocClock_lower(_ value: DocClock) -> RustBuffer {
|
||||
}
|
||||
|
||||
|
||||
public struct DocDiff {
|
||||
public var docId: String
|
||||
public var missing: String
|
||||
public var state: String
|
||||
public var timestamp: Int64
|
||||
|
||||
// Default memberwise initializers are never public by default, so we
|
||||
// declare one manually.
|
||||
public init(docId: String, missing: String, state: String, timestamp: Int64) {
|
||||
self.docId = docId
|
||||
self.missing = missing
|
||||
self.state = state
|
||||
self.timestamp = timestamp
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=6)
|
||||
extension DocDiff: Sendable {}
|
||||
#endif
|
||||
|
||||
|
||||
extension DocDiff: Equatable, Hashable {
|
||||
public static func ==(lhs: DocDiff, rhs: DocDiff) -> Bool {
|
||||
if lhs.docId != rhs.docId {
|
||||
return false
|
||||
}
|
||||
if lhs.missing != rhs.missing {
|
||||
return false
|
||||
}
|
||||
if lhs.state != rhs.state {
|
||||
return false
|
||||
}
|
||||
if lhs.timestamp != rhs.timestamp {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(docId)
|
||||
hasher.combine(missing)
|
||||
hasher.combine(state)
|
||||
hasher.combine(timestamp)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
#if swift(>=5.8)
|
||||
@_documentation(visibility: private)
|
||||
#endif
|
||||
public struct FfiConverterTypeDocDiff: FfiConverterRustBuffer {
|
||||
public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> DocDiff {
|
||||
return
|
||||
try DocDiff(
|
||||
docId: FfiConverterString.read(from: &buf),
|
||||
missing: FfiConverterString.read(from: &buf),
|
||||
state: FfiConverterString.read(from: &buf),
|
||||
timestamp: FfiConverterInt64.read(from: &buf)
|
||||
)
|
||||
}
|
||||
|
||||
public static func write(_ value: DocDiff, into buf: inout [UInt8]) {
|
||||
FfiConverterString.write(value.docId, into: &buf)
|
||||
FfiConverterString.write(value.missing, into: &buf)
|
||||
FfiConverterString.write(value.state, into: &buf)
|
||||
FfiConverterInt64.write(value.timestamp, into: &buf)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#if swift(>=5.8)
|
||||
@_documentation(visibility: private)
|
||||
#endif
|
||||
public func FfiConverterTypeDocDiff_lift(_ buf: RustBuffer) throws -> DocDiff {
|
||||
return try FfiConverterTypeDocDiff.lift(buf)
|
||||
}
|
||||
|
||||
#if swift(>=5.8)
|
||||
@_documentation(visibility: private)
|
||||
#endif
|
||||
public func FfiConverterTypeDocDiff_lower(_ value: DocDiff) -> RustBuffer {
|
||||
return FfiConverterTypeDocDiff.lower(value)
|
||||
}
|
||||
|
||||
|
||||
public struct DocIndexedClock {
|
||||
public var docId: String
|
||||
public var timestamp: Int64
|
||||
@@ -2900,6 +3015,30 @@ fileprivate struct FfiConverterOptionTypeDocClock: FfiConverterRustBuffer {
|
||||
}
|
||||
}
|
||||
|
||||
#if swift(>=5.8)
|
||||
@_documentation(visibility: private)
|
||||
#endif
|
||||
fileprivate struct FfiConverterOptionTypeDocDiff: FfiConverterRustBuffer {
|
||||
typealias SwiftType = DocDiff?
|
||||
|
||||
public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
|
||||
guard let value = value else {
|
||||
writeInt(&buf, Int8(0))
|
||||
return
|
||||
}
|
||||
writeInt(&buf, Int8(1))
|
||||
FfiConverterTypeDocDiff.write(value, into: &buf)
|
||||
}
|
||||
|
||||
public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
|
||||
switch try readInt(&buf) as Int8 {
|
||||
case 0: return nil
|
||||
case 1: return try FfiConverterTypeDocDiff.read(from: &buf)
|
||||
default: throw UniffiInternalError.unexpectedOptionalTag
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if swift(>=5.8)
|
||||
@_documentation(visibility: private)
|
||||
#endif
|
||||
@@ -3392,6 +3531,9 @@ private let initializationResult: InitializationResult = {
|
||||
if (uniffi_affine_mobile_native_checksum_method_docstoragepool_get_doc_clocks() != 46082) {
|
||||
return InitializationResult.apiChecksumMismatch
|
||||
}
|
||||
if (uniffi_affine_mobile_native_checksum_method_docstoragepool_get_doc_diff() != 22717) {
|
||||
return InitializationResult.apiChecksumMismatch
|
||||
}
|
||||
if (uniffi_affine_mobile_native_checksum_method_docstoragepool_get_doc_indexed_clock() != 17668) {
|
||||
return InitializationResult.apiChecksumMismatch
|
||||
}
|
||||
@@ -3446,6 +3588,9 @@ private let initializationResult: InitializationResult = {
|
||||
if (uniffi_affine_mobile_native_checksum_method_docstoragepool_list_blobs() != 6777) {
|
||||
return InitializationResult.apiChecksumMismatch
|
||||
}
|
||||
if (uniffi_affine_mobile_native_checksum_method_docstoragepool_merge_updates() != 49313) {
|
||||
return InitializationResult.apiChecksumMismatch
|
||||
}
|
||||
if (uniffi_affine_mobile_native_checksum_method_docstoragepool_push_update() != 60089) {
|
||||
return InitializationResult.apiChecksumMismatch
|
||||
}
|
||||
|
||||
@@ -326,6 +326,11 @@ uint64_t uniffi_affine_mobile_native_fn_method_docstoragepool_get_doc_clock(void
|
||||
uint64_t uniffi_affine_mobile_native_fn_method_docstoragepool_get_doc_clocks(void*_Nonnull ptr, RustBuffer universal_id, RustBuffer after
|
||||
);
|
||||
#endif
|
||||
#ifndef UNIFFI_FFIDEF_UNIFFI_AFFINE_MOBILE_NATIVE_FN_METHOD_DOCSTORAGEPOOL_GET_DOC_DIFF
|
||||
#define UNIFFI_FFIDEF_UNIFFI_AFFINE_MOBILE_NATIVE_FN_METHOD_DOCSTORAGEPOOL_GET_DOC_DIFF
|
||||
uint64_t uniffi_affine_mobile_native_fn_method_docstoragepool_get_doc_diff(void*_Nonnull ptr, RustBuffer universal_id, RustBuffer doc_id, RustBuffer state
|
||||
);
|
||||
#endif
|
||||
#ifndef UNIFFI_FFIDEF_UNIFFI_AFFINE_MOBILE_NATIVE_FN_METHOD_DOCSTORAGEPOOL_GET_DOC_INDEXED_CLOCK
|
||||
#define UNIFFI_FFIDEF_UNIFFI_AFFINE_MOBILE_NATIVE_FN_METHOD_DOCSTORAGEPOOL_GET_DOC_INDEXED_CLOCK
|
||||
uint64_t uniffi_affine_mobile_native_fn_method_docstoragepool_get_doc_indexed_clock(void*_Nonnull ptr, RustBuffer universal_id, RustBuffer doc_id
|
||||
@@ -416,6 +421,11 @@ uint64_t uniffi_affine_mobile_native_fn_method_docstoragepool_invalidate_peer_wo
|
||||
uint64_t uniffi_affine_mobile_native_fn_method_docstoragepool_list_blobs(void*_Nonnull ptr, RustBuffer universal_id
|
||||
);
|
||||
#endif
|
||||
#ifndef UNIFFI_FFIDEF_UNIFFI_AFFINE_MOBILE_NATIVE_FN_METHOD_DOCSTORAGEPOOL_MERGE_UPDATES
|
||||
#define UNIFFI_FFIDEF_UNIFFI_AFFINE_MOBILE_NATIVE_FN_METHOD_DOCSTORAGEPOOL_MERGE_UPDATES
|
||||
RustBuffer uniffi_affine_mobile_native_fn_method_docstoragepool_merge_updates(void*_Nonnull ptr, RustBuffer updates, RustCallStatus *_Nonnull out_status
|
||||
);
|
||||
#endif
|
||||
#ifndef UNIFFI_FFIDEF_UNIFFI_AFFINE_MOBILE_NATIVE_FN_METHOD_DOCSTORAGEPOOL_PUSH_UPDATE
|
||||
#define UNIFFI_FFIDEF_UNIFFI_AFFINE_MOBILE_NATIVE_FN_METHOD_DOCSTORAGEPOOL_PUSH_UPDATE
|
||||
uint64_t uniffi_affine_mobile_native_fn_method_docstoragepool_push_update(void*_Nonnull ptr, RustBuffer universal_id, RustBuffer doc_id, RustBuffer update, RustBuffer create_for_peer
|
||||
@@ -867,6 +877,12 @@ uint16_t uniffi_affine_mobile_native_checksum_method_docstoragepool_get_doc_cloc
|
||||
#define UNIFFI_FFIDEF_UNIFFI_AFFINE_MOBILE_NATIVE_CHECKSUM_METHOD_DOCSTORAGEPOOL_GET_DOC_CLOCKS
|
||||
uint16_t uniffi_affine_mobile_native_checksum_method_docstoragepool_get_doc_clocks(void
|
||||
|
||||
);
|
||||
#endif
|
||||
#ifndef UNIFFI_FFIDEF_UNIFFI_AFFINE_MOBILE_NATIVE_CHECKSUM_METHOD_DOCSTORAGEPOOL_GET_DOC_DIFF
|
||||
#define UNIFFI_FFIDEF_UNIFFI_AFFINE_MOBILE_NATIVE_CHECKSUM_METHOD_DOCSTORAGEPOOL_GET_DOC_DIFF
|
||||
uint16_t uniffi_affine_mobile_native_checksum_method_docstoragepool_get_doc_diff(void
|
||||
|
||||
);
|
||||
#endif
|
||||
#ifndef UNIFFI_FFIDEF_UNIFFI_AFFINE_MOBILE_NATIVE_CHECKSUM_METHOD_DOCSTORAGEPOOL_GET_DOC_INDEXED_CLOCK
|
||||
@@ -975,6 +991,12 @@ uint16_t uniffi_affine_mobile_native_checksum_method_docstoragepool_invalidate_p
|
||||
#define UNIFFI_FFIDEF_UNIFFI_AFFINE_MOBILE_NATIVE_CHECKSUM_METHOD_DOCSTORAGEPOOL_LIST_BLOBS
|
||||
uint16_t uniffi_affine_mobile_native_checksum_method_docstoragepool_list_blobs(void
|
||||
|
||||
);
|
||||
#endif
|
||||
#ifndef UNIFFI_FFIDEF_UNIFFI_AFFINE_MOBILE_NATIVE_CHECKSUM_METHOD_DOCSTORAGEPOOL_MERGE_UPDATES
|
||||
#define UNIFFI_FFIDEF_UNIFFI_AFFINE_MOBILE_NATIVE_CHECKSUM_METHOD_DOCSTORAGEPOOL_MERGE_UPDATES
|
||||
uint16_t uniffi_affine_mobile_native_checksum_method_docstoragepool_merge_updates(void
|
||||
|
||||
);
|
||||
#endif
|
||||
#ifndef UNIFFI_FFIDEF_UNIFFI_AFFINE_MOBILE_NATIVE_CHECKSUM_METHOD_DOCSTORAGEPOOL_PUSH_UPDATE
|
||||
|
||||
@@ -36,13 +36,13 @@ platform :ios do
|
||||
api_key = release_api_key
|
||||
current_build_number = app_store_build_number(live: false, api_key: api_key)
|
||||
increment_build_number(xcodeproj: 'App.xcodeproj', build_number: current_build_number + 1)
|
||||
build_app(
|
||||
ipa_path = build_app(
|
||||
workspace: 'App.xcworkspace', scheme: 'App', configuration: 'Release',
|
||||
output_directory: 'release', output_name: 'AFFiNE.ipa',
|
||||
export_method: 'app-store', skip_profile_detection: true,
|
||||
export_options: {signingStyle: 'manual', provisioningProfiles: provisioning_profiles}
|
||||
)
|
||||
File.write('release/store-build.json', JSON.generate({
|
||||
File.write(File.join(File.dirname(ipa_path), 'store-build.json'), JSON.generate({
|
||||
appIdentifier: CredentialsManager::AppfileConfig.try_fetch_value(:app_identifier),
|
||||
version: get_version_number(xcodeproj: 'App.xcodeproj', target: 'AFFiNE'),
|
||||
buildNumber: (current_build_number + 1).to_s
|
||||
|
||||
@@ -914,5 +914,11 @@ function createStoreManagerClient() {
|
||||
{ type: 'auth-access-token-channel', port: authTokenChannelClient },
|
||||
[authTokenChannelClient]
|
||||
);
|
||||
return new StoreManagerClient(new OpClient(worker));
|
||||
const nativeMergeUpdates = NbStoreNativeDBApis.mergeUpdates;
|
||||
return new StoreManagerClient(new OpClient(worker), {
|
||||
mergeUpdates: nativeMergeUpdates
|
||||
? updates =>
|
||||
updates.length === 1 ? updates[0] : nativeMergeUpdates(updates)
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
import { idbStoragesIndexerOnly } from '@affine/nbstore/idb';
|
||||
import {
|
||||
bindNativeDBApis,
|
||||
getNativeMergeUpdates,
|
||||
type NativeDBApis,
|
||||
sqliteStorages,
|
||||
} from '@affine/nbstore/sqlite';
|
||||
@@ -66,11 +67,25 @@ const consumer = new OpConsumer<WorkerManagerOps>(
|
||||
globalThis as MessageCommunicapable
|
||||
);
|
||||
|
||||
const storeManager = new StoreManagerConsumer([
|
||||
...idbStoragesIndexerOnly,
|
||||
...sqliteStorages,
|
||||
...broadcastChannelStorages,
|
||||
...cloudStorages,
|
||||
]);
|
||||
const storeManager = new StoreManagerConsumer(
|
||||
[
|
||||
...idbStoragesIndexerOnly,
|
||||
...sqliteStorages,
|
||||
...broadcastChannelStorages,
|
||||
...cloudStorages,
|
||||
],
|
||||
{
|
||||
mergeUpdates: updates => {
|
||||
if (updates.length === 1) {
|
||||
return updates[0];
|
||||
}
|
||||
const nativeMerge = getNativeMergeUpdates();
|
||||
if (!nativeMerge) {
|
||||
throw new Error('Native mergeUpdates is not bound');
|
||||
}
|
||||
return nativeMerge(updates);
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
storeManager.bindConsumer(consumer);
|
||||
@@ -67,6 +67,15 @@ export interface NbStorePlugin {
|
||||
id: string;
|
||||
docId: string;
|
||||
}) => Promise<{ docId: string; bin: string; timestamp: number } | undefined>;
|
||||
getDocDiff: (options: {
|
||||
id: string;
|
||||
docId: string;
|
||||
state?: string;
|
||||
}) => Promise<
|
||||
| { docId: string; missing: string; state: string; timestamp: number }
|
||||
| undefined
|
||||
>;
|
||||
mergeUpdates: (options: { updates: string[] }) => Promise<{ bin: string }>;
|
||||
deleteDoc: (options: { id: string; docId: string }) => Promise<void>;
|
||||
getDocClocks: (options: { id: string; after?: number | null }) => Promise<{
|
||||
clocks: {
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
type BlobRecord,
|
||||
type CrawlResult,
|
||||
type DocClock,
|
||||
type DocDiff,
|
||||
type DocIndexedClock,
|
||||
type DocRecord,
|
||||
type ListedBlobRecord,
|
||||
@@ -60,6 +61,32 @@ export const NbStoreNativeDBApis: NativeDBApis = {
|
||||
}
|
||||
: null;
|
||||
},
|
||||
getDocDiff: async function (
|
||||
id: string,
|
||||
docId: string,
|
||||
state?: Uint8Array
|
||||
): Promise<DocDiff | null> {
|
||||
const diff = await NbStore.getDocDiff({
|
||||
id,
|
||||
docId,
|
||||
state: state ? await uint8ArrayToBase64(state) : undefined,
|
||||
});
|
||||
return diff
|
||||
? {
|
||||
docId: diff.docId,
|
||||
missing: base64ToUint8Array(diff.missing),
|
||||
state: base64ToUint8Array(diff.state),
|
||||
timestamp: new Date(diff.timestamp),
|
||||
}
|
||||
: null;
|
||||
},
|
||||
mergeUpdates: async function (updates: Uint8Array[]): Promise<Uint8Array> {
|
||||
const encoded = await Promise.all(
|
||||
updates.map(update => uint8ArrayToBase64(update))
|
||||
);
|
||||
const { bin } = await NbStore.mergeUpdates({ updates: encoded });
|
||||
return base64ToUint8Array(bin);
|
||||
},
|
||||
deleteDoc: async function (id: string, docId: string): Promise<void> {
|
||||
await NbStore.deleteDoc({
|
||||
id,
|
||||
|
||||
@@ -21,6 +21,16 @@ pub struct DocRecord {
|
||||
pub timestamp: i64,
|
||||
}
|
||||
|
||||
#[derive(uniffi::Record)]
|
||||
pub struct DocDiff {
|
||||
pub doc_id: String,
|
||||
// base64 encoded data
|
||||
pub missing: String,
|
||||
// base64 encoded data
|
||||
pub state: String,
|
||||
pub timestamp: i64,
|
||||
}
|
||||
|
||||
#[derive(uniffi::Record)]
|
||||
pub struct DocClock {
|
||||
pub doc_id: String,
|
||||
|
||||
@@ -14,8 +14,8 @@ use affine_common::hashcash::Stamp;
|
||||
pub(crate) use error::Result;
|
||||
pub use error::UniffiError;
|
||||
pub use ffi_types::{
|
||||
Blob, BlockInfo, CrawlResult, DocClock, DocIndexedClock, DocRecord, IndexAggregateResult, IndexBucket, IndexField,
|
||||
IndexHighlight, IndexHighlightValue, IndexHit, IndexSearchResult, IndexSpan, ListedBlob, SetBlob,
|
||||
Blob, BlockInfo, CrawlResult, DocClock, DocDiff, DocIndexedClock, DocRecord, IndexAggregateResult, IndexBucket,
|
||||
IndexField, IndexHighlight, IndexHighlightValue, IndexHit, IndexSearchResult, IndexSpan, ListedBlob, SetBlob,
|
||||
};
|
||||
#[cfg(any(target_os = "android", target_os = "ios"))]
|
||||
pub use preview::{render_mermaid_preview_svg, render_typst_preview_svg};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::*;
|
||||
use crate::DocDiff;
|
||||
|
||||
#[uniffi::export(async_runtime = "tokio")]
|
||||
impl DocStoragePool {
|
||||
@@ -17,6 +18,41 @@ impl DocStoragePool {
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn get_doc_diff(
|
||||
&self,
|
||||
universal_id: String,
|
||||
doc_id: String,
|
||||
state: Option<String>,
|
||||
) -> Result<Option<DocDiff>> {
|
||||
let remote_state_vector = state.as_deref().map(decode_base64_data).transpose()?;
|
||||
let Some(diff) = self
|
||||
.inner
|
||||
.get(universal_id)
|
||||
.await?
|
||||
.get_doc_diff(doc_id, remote_state_vector)
|
||||
.await?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let timestamp = diff.timestamp.and_utc().timestamp_millis();
|
||||
Ok(Some(DocDiff {
|
||||
doc_id: diff.doc_id,
|
||||
missing: encode_base64_data(&diff.missing),
|
||||
state: encode_base64_data(&diff.state),
|
||||
timestamp,
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn merge_updates(&self, updates: Vec<String>) -> Result<String> {
|
||||
let decoded: Vec<Vec<u8>> = updates
|
||||
.iter()
|
||||
.map(|u| decode_base64_data(u))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let slices: Vec<&[u8]> = decoded.iter().map(|u| u.as_slice()).collect();
|
||||
let merged = affine_nbstore::merge_updates(&slices)?;
|
||||
Ok(encode_base64_data(&merged))
|
||||
}
|
||||
|
||||
pub async fn delete_doc(&self, universal_id: String, doc_id: String) -> Result<()> {
|
||||
Ok(self.inner.get(universal_id).await?.delete_doc(doc_id).await?)
|
||||
}
|
||||
|
||||
Vendored
+19
@@ -82,6 +82,8 @@ export declare class DiskSyncSubscriber {
|
||||
|
||||
export declare function cancelImportSession(sessionId: string): void
|
||||
|
||||
export declare function compactDocUpdatesV1(updates: Array<Uint8Array>): Uint8Array
|
||||
|
||||
export interface CreateImportBatchLimits {
|
||||
maxDocs?: number
|
||||
maxBlobs?: number
|
||||
@@ -156,6 +158,8 @@ export declare function mintChallengeResponse(resource: string, bits?: number |
|
||||
|
||||
export declare function nextImportBatch(sessionId: string): string | null
|
||||
|
||||
export declare function parseWorkspaceRootDocMeta(updates: Array<Uint8Array>): WorkspaceRootDocMeta
|
||||
|
||||
export declare function renderMermaidSvg(request: MermaidRenderRequest): MermaidRenderResult
|
||||
|
||||
export declare function renderTypstSvg(request: TypstRenderRequest): TypstRenderResult
|
||||
@@ -175,6 +179,12 @@ export interface TypstRenderResult {
|
||||
}
|
||||
|
||||
export declare function verifyChallengeResponse(response: string, bits: number, resource: string): Promise<boolean>
|
||||
|
||||
export interface WorkspaceRootDocMeta {
|
||||
name?: string
|
||||
avatar?: string
|
||||
pageCount?: number
|
||||
}
|
||||
export declare class DocStorage {
|
||||
constructor(path: string)
|
||||
validate(): Promise<boolean>
|
||||
@@ -198,6 +208,8 @@ export declare class DocStoragePool {
|
||||
installPeerWorkspaceState(universalId: string, peer: string, rootDocId: string, cacheToken: number, docs: Array<WorkspaceDoc>, clocks: Record<string, number>): Promise<boolean>
|
||||
confirmPeerDocCreate(universalId: string, peer: string, docId: string): Promise<void>
|
||||
getDoc(universalId: string, docId: string): Promise<DocRecord | null>
|
||||
mergeUpdates(updates: Array<Uint8Array>): Uint8Array
|
||||
getDocDiff(universalId: string, docId: string, state?: Uint8Array | undefined | null): Promise<DocDiff | null>
|
||||
readDocRecordsReadonly(path: string, docId: string): Promise<ReadonlyDocRecords>
|
||||
readBlobReadonly(path: string, key: string): Promise<Blob | null>
|
||||
deleteDoc(universalId: string, docId: string): Promise<void>
|
||||
@@ -246,6 +258,13 @@ export interface DocClock {
|
||||
timestamp: Date
|
||||
}
|
||||
|
||||
export interface DocDiff {
|
||||
docId: string
|
||||
missing: Uint8Array
|
||||
state: Uint8Array
|
||||
timestamp: Date
|
||||
}
|
||||
|
||||
export interface DocIndexedClock {
|
||||
docId: string
|
||||
timestamp: Date
|
||||
|
||||
@@ -584,10 +584,12 @@ module.exports.stopRecording = nativeBinding.stopRecording
|
||||
module.exports.DiskSync = nativeBinding.DiskSync
|
||||
module.exports.DiskSyncSubscriber = nativeBinding.DiskSyncSubscriber
|
||||
module.exports.cancelImportSession = nativeBinding.cancelImportSession
|
||||
module.exports.compactDocUpdatesV1 = nativeBinding.compactDocUpdatesV1
|
||||
module.exports.createImportSession = nativeBinding.createImportSession
|
||||
module.exports.disposeImportSession = nativeBinding.disposeImportSession
|
||||
module.exports.mintChallengeResponse = nativeBinding.mintChallengeResponse
|
||||
module.exports.nextImportBatch = nativeBinding.nextImportBatch
|
||||
module.exports.parseWorkspaceRootDocMeta = nativeBinding.parseWorkspaceRootDocMeta
|
||||
module.exports.renderMermaidSvg = nativeBinding.renderMermaidSvg
|
||||
module.exports.renderTypstSvg = nativeBinding.renderTypstSvg
|
||||
module.exports.verifyChallengeResponse = nativeBinding.verifyChallengeResponse
|
||||
|
||||
@@ -2,14 +2,32 @@ use std::ops::Deref;
|
||||
|
||||
use chrono::{DateTime, NaiveDateTime};
|
||||
use sqlx::{QueryBuilder, Row};
|
||||
use y_octo::merge_updates_v1;
|
||||
use y_octo::{diff_update_v1, encode_state_vector_from_update_v1, merge_updates_v1, validate_update_v1};
|
||||
|
||||
use super::{
|
||||
DocClock, DocRecord, DocUpdate, ReadonlyDocRecords,
|
||||
DocClock, DocDiff, DocRecord, DocUpdate, ReadonlyDocRecords,
|
||||
error::{Error, Result},
|
||||
storage::SqliteDocStorage,
|
||||
};
|
||||
|
||||
fn is_empty_update(bin: &[u8]) -> bool {
|
||||
bin.is_empty() || bin == [0, 0]
|
||||
}
|
||||
|
||||
pub fn merge_updates(updates: &[&[u8]]) -> Result<Vec<u8>> {
|
||||
let non_empty: Vec<&[u8]> = updates.iter().copied().filter(|u| !is_empty_update(u)).collect();
|
||||
match non_empty.as_slice() {
|
||||
[] => Ok(vec![0, 0]),
|
||||
[single] => {
|
||||
validate_update_v1(single).map_err(|_| Error::InvalidBinary)?;
|
||||
Ok((*single).to_vec())
|
||||
}
|
||||
many => merge_updates_v1(many.iter().copied())
|
||||
.and_then(|merged| merged.encode_v1())
|
||||
.map_err(|_| Error::InvalidBinary),
|
||||
}
|
||||
}
|
||||
|
||||
struct Meta {
|
||||
space_id: String,
|
||||
}
|
||||
@@ -283,6 +301,67 @@ impl SqliteDocStorage {
|
||||
Err(Error::ConcurrentModification)
|
||||
}
|
||||
|
||||
pub async fn get_doc_diff(&self, doc_id: String, remote_state_vector: Option<Vec<u8>>) -> Result<Option<DocDiff>> {
|
||||
let mut read_tx = self.pool.begin().await?;
|
||||
let snapshot = sqlx::query_as!(
|
||||
DocRecord,
|
||||
"SELECT doc_id, data as bin, updated_at as timestamp FROM snapshots WHERE doc_id = ?",
|
||||
doc_id
|
||||
)
|
||||
.fetch_optional(&mut *read_tx)
|
||||
.await?;
|
||||
let updates = sqlx::query_as!(
|
||||
DocUpdate,
|
||||
"SELECT doc_id, created_at as timestamp, data as bin FROM updates WHERE doc_id = ? ORDER BY created_at",
|
||||
doc_id
|
||||
)
|
||||
.fetch_all(&mut *read_tx)
|
||||
.await?;
|
||||
read_tx.commit().await?;
|
||||
|
||||
if snapshot.is_none() && updates.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let timestamp = updates
|
||||
.last()
|
||||
.map(|update| update.timestamp)
|
||||
.into_iter()
|
||||
.chain(snapshot.as_ref().map(|record| record.timestamp))
|
||||
.max()
|
||||
.expect("snapshot or updates is non-empty");
|
||||
|
||||
let merged_bin = if updates.is_empty() {
|
||||
snapshot.expect("snapshot is non-empty").bin.to_vec()
|
||||
} else {
|
||||
let mut segments = Vec::with_capacity(updates.len() + usize::from(snapshot.is_some()));
|
||||
if let Some(record) = &snapshot {
|
||||
segments.push(record.bin.to_vec());
|
||||
}
|
||||
segments.extend(updates.iter().map(|update| update.bin.to_vec()));
|
||||
merge_updates_v1(segments)
|
||||
.map_err(|_| affine_doc_loader::ParseError::InvalidBinary)?
|
||||
.encode_v1()
|
||||
.map_err(|_| affine_doc_loader::ParseError::InvalidBinary)?
|
||||
};
|
||||
|
||||
let state =
|
||||
encode_state_vector_from_update_v1(&merged_bin).map_err(|_| affine_doc_loader::ParseError::InvalidBinary)?;
|
||||
let missing = match remote_state_vector.as_deref() {
|
||||
Some(sv) if !sv.is_empty() => {
|
||||
diff_update_v1(&merged_bin, sv).map_err(|_| affine_doc_loader::ParseError::InvalidBinary)?
|
||||
}
|
||||
_ => merged_bin,
|
||||
};
|
||||
|
||||
Ok(Some(DocDiff {
|
||||
doc_id,
|
||||
missing: missing.into(),
|
||||
state: state.into(),
|
||||
timestamp,
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn set_doc_snapshot(&self, snapshot: DocRecord) -> Result<bool> {
|
||||
let result = sqlx::query(
|
||||
r#"
|
||||
@@ -798,6 +877,101 @@ mod tests {
|
||||
assert_eq!(clock.unwrap().doc_id, "test_1");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_doc_diff_handles_missing_empty_and_remote_state_vectors() {
|
||||
let storage = get_storage().await;
|
||||
|
||||
// 1. Non-existent doc returns None
|
||||
assert!(
|
||||
storage
|
||||
.get_doc_diff("missing".to_string(), None)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
|
||||
// Build a doc with snapshot + multiple uncompressed updates
|
||||
let doc = DocOptions::new().with_client_id(11).build();
|
||||
let mut text = doc.get_or_create_text("content").unwrap();
|
||||
text.insert(0, "alpha").unwrap();
|
||||
let snap_bin = doc.encode_update_v1().unwrap();
|
||||
let sv_after_snap = doc.get_state_vector().encode_v1().unwrap();
|
||||
|
||||
text.insert(5, " beta").unwrap();
|
||||
let u1 = doc
|
||||
.encode_state_as_update_v1(&y_octo::StateVector::decode_v1(&sv_after_snap).unwrap())
|
||||
.unwrap();
|
||||
let sv_after_u1 = doc.get_state_vector().encode_v1().unwrap();
|
||||
|
||||
text.insert(10, " gamma").unwrap();
|
||||
let u2 = doc
|
||||
.encode_state_as_update_v1(&y_octo::StateVector::decode_v1(&sv_after_u1).unwrap())
|
||||
.unwrap();
|
||||
let full_sv = doc.get_state_vector().encode_v1().unwrap();
|
||||
|
||||
let snap_ts = DateTime::from_timestamp_millis(1_700_000_000_000).unwrap().naive_utc();
|
||||
storage
|
||||
.set_doc_snapshot(DocRecord {
|
||||
doc_id: "doc-diff".to_string(),
|
||||
bin: snap_bin.into(),
|
||||
timestamp: snap_ts,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let _t1 = storage.push_update("doc-diff".to_string(), u1).await.unwrap();
|
||||
let t2 = storage.push_update("doc-diff".to_string(), u2).await.unwrap();
|
||||
|
||||
// 2. None and Some(vec![]) return full merged snapshot
|
||||
for sv in [None, Some(Vec::new())] {
|
||||
let diff = storage.get_doc_diff("doc-diff".to_string(), sv).await.unwrap().unwrap();
|
||||
assert_eq!(diff.doc_id, "doc-diff");
|
||||
assert_eq!(diff.timestamp, t2);
|
||||
assert_eq!(diff.state.deref(), full_sv.as_slice());
|
||||
let restored = y_octo::Doc::try_from_binary_v1(&diff.missing).unwrap();
|
||||
assert_eq!(
|
||||
restored.get_or_create_text("content").unwrap().to_string(),
|
||||
"alpha beta gamma"
|
||||
);
|
||||
}
|
||||
|
||||
// 3. Some(vec![0]) returns full diff from empty state vector
|
||||
let diff_zero = storage
|
||||
.get_doc_diff("doc-diff".to_string(), Some(vec![0]))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(diff_zero.state.deref(), full_sv.as_slice());
|
||||
let restored_zero = y_octo::Doc::try_from_binary_v1(&diff_zero.missing).unwrap();
|
||||
assert_eq!(
|
||||
restored_zero.get_or_create_text("content").unwrap().to_string(),
|
||||
"alpha beta gamma"
|
||||
);
|
||||
|
||||
// 4. Real remote SV returns incremental diff only
|
||||
let diff_inc = storage
|
||||
.get_doc_diff("doc-diff".to_string(), Some(sv_after_snap))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(diff_inc.state.deref(), full_sv.as_slice());
|
||||
let mut remote = DocOptions::new().with_client_id(99).build();
|
||||
remote
|
||||
.apply_update_from_binary_v1(
|
||||
&storage
|
||||
.get_doc_snapshot("doc-diff".to_string())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.bin,
|
||||
)
|
||||
.unwrap();
|
||||
remote.apply_update_from_binary_v1(&diff_inc.missing).unwrap();
|
||||
assert_eq!(
|
||||
remote.get_or_create_text("content").unwrap().to_string(),
|
||||
"alpha beta gamma"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mark_updates_merged() {
|
||||
let storage = get_storage().await;
|
||||
@@ -824,4 +998,31 @@ mod tests {
|
||||
|
||||
assert_eq!(updates.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_updates_handles_empty_single_multiple_and_invalid() {
|
||||
use y_octo::DocOptions;
|
||||
|
||||
assert_eq!(merge_updates(&[]).unwrap(), vec![0, 0]);
|
||||
assert_eq!(merge_updates(&[&[], &[0, 0]]).unwrap(), vec![0, 0]);
|
||||
|
||||
let doc1 = DocOptions::new().with_client_id(1).build();
|
||||
doc1.get_or_create_text("content").unwrap().insert(0, "hello").unwrap();
|
||||
let u1 = doc1.encode_update_v1().unwrap();
|
||||
|
||||
let doc2 = DocOptions::new().with_client_id(2).build();
|
||||
doc2.get_or_create_text("content").unwrap().insert(0, " world").unwrap();
|
||||
let u2 = doc2.encode_update_v1().unwrap();
|
||||
|
||||
assert_eq!(merge_updates(&[&u1, &[0, 0]]).unwrap(), u1);
|
||||
|
||||
let merged = merge_updates(&[&u1, &u2]).unwrap();
|
||||
let mut check = DocOptions::new().build();
|
||||
check.apply_update_from_binary_v1(&merged).unwrap();
|
||||
let text = check.get_or_create_text("content").unwrap().to_string();
|
||||
assert!(text.contains("hello") && text.contains("world"));
|
||||
|
||||
assert!(matches!(merge_updates(&[&[0xff]]), Err(Error::InvalidBinary)));
|
||||
assert!(matches!(merge_updates(&[&u1, &[0xff]]), Err(Error::InvalidBinary)));
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,8 @@ pub enum Error {
|
||||
InvalidOperation,
|
||||
#[error("Index is rebuilding")]
|
||||
IndexNotReady,
|
||||
#[error("invalid_binary")]
|
||||
InvalidBinary,
|
||||
#[error("Serialization Error: {0}")]
|
||||
Serialization(String),
|
||||
#[error("Document changed during compaction")]
|
||||
|
||||
@@ -11,6 +11,7 @@ pub mod storage;
|
||||
#[cfg(not(feature = "use-as-lib"))]
|
||||
use affine_common::napi_utils::to_napi_error;
|
||||
use chrono::NaiveDateTime;
|
||||
pub use doc::merge_updates;
|
||||
use napi::bindgen_prelude::*;
|
||||
#[cfg(not(feature = "use-as-lib"))]
|
||||
use napi_derive::napi;
|
||||
@@ -47,6 +48,16 @@ pub struct DocRecord {
|
||||
pub timestamp: NaiveDateTime,
|
||||
}
|
||||
|
||||
#[cfg_attr(not(feature = "use-as-lib"), napi(object))]
|
||||
pub struct DocDiff {
|
||||
pub doc_id: String,
|
||||
#[cfg_attr(not(feature = "use-as-lib"), napi(ts_type = "Uint8Array"))]
|
||||
pub missing: Data,
|
||||
#[cfg_attr(not(feature = "use-as-lib"), napi(ts_type = "Uint8Array"))]
|
||||
pub state: Data,
|
||||
pub timestamp: NaiveDateTime,
|
||||
}
|
||||
|
||||
#[cfg_attr(not(feature = "use-as-lib"), napi(object))]
|
||||
pub struct ReadonlyDocRecords {
|
||||
pub snapshot: Option<DocRecord>,
|
||||
@@ -258,6 +269,28 @@ impl DocStoragePool {
|
||||
Ok(self.get(universal_id).await?.get_doc(doc_id).await?)
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn merge_updates(&self, updates: Vec<Uint8Array>) -> Result<Uint8Array> {
|
||||
let slices: Vec<&[u8]> = updates.iter().map(|u| u.as_ref()).collect();
|
||||
Ok(Uint8Array::new(doc::merge_updates(&slices)?))
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub async fn get_doc_diff(
|
||||
&self,
|
||||
universal_id: String,
|
||||
doc_id: String,
|
||||
state: Option<Uint8Array>,
|
||||
) -> Result<Option<DocDiff>> {
|
||||
Ok(
|
||||
self
|
||||
.get(universal_id)
|
||||
.await?
|
||||
.get_doc_diff(doc_id, state.map(|s| s.to_vec()))
|
||||
.await?,
|
||||
)
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub async fn read_doc_records_readonly(&self, path: String, doc_id: String) -> Result<ReadonlyDocRecords> {
|
||||
Ok(SqliteDocStorage::read_doc_records_readonly(&path, &doc_id).await?)
|
||||
|
||||
@@ -1,49 +1,51 @@
|
||||
use std::collections::HashMap;
|
||||
use std::{collections::HashMap, fmt};
|
||||
|
||||
use chrono::Utc;
|
||||
use y_octo::{Any, Array, Doc, Map, Value};
|
||||
|
||||
use super::{
|
||||
frontmatter::{parse_bool, parse_tags},
|
||||
types::FrontmatterMeta,
|
||||
utils::{is_empty_update, load_doc_or_new},
|
||||
use affine_doc_loader::{
|
||||
ParseError, RootPageMetaPatch, build_root_meta_update as loader_build_root_meta_update,
|
||||
extract_all_root_meta as loader_extract_all_root_meta,
|
||||
};
|
||||
use chrono::Utc;
|
||||
|
||||
use super::{frontmatter::normalize_tags, types::FrontmatterMeta};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum RootMetaUpdateError {
|
||||
InvalidRootShape(String),
|
||||
Other(String),
|
||||
}
|
||||
|
||||
impl fmt::Display for RootMetaUpdateError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::InvalidRootShape(msg) => write!(f, "invalid root shape: {msg}"),
|
||||
Self::Other(msg) => f.write_str(msg),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn build_root_meta_update(
|
||||
existing_root: &[u8],
|
||||
workspace_id: &str,
|
||||
_workspace_id: &str,
|
||||
doc_id: &str,
|
||||
meta: &FrontmatterMeta,
|
||||
) -> Result<Vec<u8>, String> {
|
||||
let doc = load_doc_or_new(existing_root, Some(workspace_id))?;
|
||||
|
||||
let state_before = doc.get_state_vector();
|
||||
let mut meta_map = doc
|
||||
.get_or_create_map("meta")
|
||||
.map_err(|err| format!("failed to open root meta map: {}", err))?;
|
||||
let mut pages = ensure_pages_array(&doc, &mut meta_map)?;
|
||||
|
||||
let mut page = match pages
|
||||
.iter()
|
||||
.filter_map(|value| value.to_map())
|
||||
.find(|page| get_string_from_map(page, "id").as_deref() == Some(doc_id))
|
||||
{
|
||||
Some(page) => page,
|
||||
None => {
|
||||
let page = doc
|
||||
.create_map()
|
||||
.map_err(|err| format!("failed to create root page map: {err}"))?;
|
||||
pages
|
||||
.push(Value::Map(page.clone()))
|
||||
.map_err(|err| format!("failed to insert root page map: {err}"))?;
|
||||
page
|
||||
}
|
||||
) -> Result<Vec<u8>, RootMetaUpdateError> {
|
||||
let patch = RootPageMetaPatch {
|
||||
title: meta.title.clone(),
|
||||
create_date: None,
|
||||
trash: meta.trash,
|
||||
trash_date: None,
|
||||
favorite: meta.favorite,
|
||||
tags: normalize_tags(meta.tags.clone()),
|
||||
updated_date: Some(Utc::now().timestamp_millis()),
|
||||
};
|
||||
apply_page_meta(&doc, &mut page, doc_id, meta)?;
|
||||
|
||||
doc
|
||||
.encode_state_as_update_v1(&state_before)
|
||||
.map_err(|err| format!("failed to encode root meta update: {}", err))
|
||||
match loader_build_root_meta_update(existing_root, doc_id, &patch) {
|
||||
Ok(Some(delta)) => Ok(delta),
|
||||
Ok(None) => Ok(vec![0, 0]),
|
||||
Err(ParseError::InvalidRootShape(msg)) => Err(RootMetaUpdateError::InvalidRootShape(msg)),
|
||||
Err(err) => Err(RootMetaUpdateError::Other(format!(
|
||||
"failed to build root meta update: {err}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn extract_root_meta_for_doc(root_bin: &[u8], doc_id: &str) -> Result<Option<FrontmatterMeta>, String> {
|
||||
@@ -52,288 +54,19 @@ pub(crate) fn extract_root_meta_for_doc(root_bin: &[u8], doc_id: &str) -> Result
|
||||
}
|
||||
|
||||
pub(crate) fn extract_all_root_meta(root_bin: &[u8]) -> Result<HashMap<String, FrontmatterMeta>, String> {
|
||||
if is_empty_update(root_bin) {
|
||||
return Ok(HashMap::new());
|
||||
let pages = loader_extract_all_root_meta(root_bin).map_err(|err| format!("failed to extract root meta: {err}"))?;
|
||||
let mut result = HashMap::with_capacity(pages.len());
|
||||
for page in pages {
|
||||
result.insert(
|
||||
page.id.clone(),
|
||||
FrontmatterMeta {
|
||||
id: Some(page.id),
|
||||
title: page.title,
|
||||
tags: page.tags,
|
||||
favorite: page.favorite,
|
||||
trash: page.trash,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let doc = load_doc_or_new(root_bin, None)?;
|
||||
let meta = match doc.get_map("meta") {
|
||||
Ok(meta) => meta,
|
||||
Err(_) => return Ok(HashMap::new()),
|
||||
};
|
||||
|
||||
let pages_value = meta.get("pages");
|
||||
let mut result = HashMap::new();
|
||||
|
||||
if let Some(pages) = pages_value.as_ref().and_then(|value| value.to_array()) {
|
||||
for page_value in pages.iter() {
|
||||
let Some(page_map) = page_value.to_map() else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let Some(doc_id) = get_string_from_map(&page_map, "id") else {
|
||||
continue;
|
||||
};
|
||||
|
||||
result.insert(doc_id.clone(), extract_meta_from_page_map(&page_map, Some(doc_id)));
|
||||
}
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
if let Some(Any::Array(entries)) = pages_value.and_then(|value| value.to_any()) {
|
||||
for entry in entries {
|
||||
let Any::Object(values) = entry else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let Some(Any::String(doc_id)) = values.get("id") else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let mut meta = FrontmatterMeta {
|
||||
id: Some(doc_id.clone()),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
if let Some(Any::String(title)) = values.get("title") {
|
||||
meta.title = Some(title.clone());
|
||||
}
|
||||
if let Some(tags) = values.get("tags") {
|
||||
meta.tags = extract_tags_from_any(tags);
|
||||
}
|
||||
if let Some(value) = values.get("favorite") {
|
||||
meta.favorite = any_to_bool(value);
|
||||
}
|
||||
if let Some(value) = values.get("trash") {
|
||||
meta.trash = any_to_bool(value);
|
||||
}
|
||||
|
||||
result.insert(doc_id.clone(), meta);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn apply_page_meta(doc: &Doc, page: &mut Map, doc_id: &str, meta: &FrontmatterMeta) -> Result<(), String> {
|
||||
page
|
||||
.insert("id".to_string(), Any::String(doc_id.to_string()))
|
||||
.map_err(|err| format!("failed to set root meta id: {}", err))?;
|
||||
|
||||
if let Some(title) = meta.title.as_ref() {
|
||||
page
|
||||
.insert("title".to_string(), Any::String(title.clone()))
|
||||
.map_err(|err| format!("failed to set root meta title: {}", err))?;
|
||||
}
|
||||
|
||||
if let Some(tags) = super::frontmatter::normalize_tags(meta.tags.clone()) {
|
||||
let mut tags_array = doc
|
||||
.create_array()
|
||||
.map_err(|err| format!("failed to create tags array: {}", err))?;
|
||||
for tag in tags {
|
||||
tags_array
|
||||
.push(Any::String(tag))
|
||||
.map_err(|err| format!("failed to push tag: {}", err))?;
|
||||
}
|
||||
|
||||
page
|
||||
.insert("tags".to_string(), Value::Array(tags_array))
|
||||
.map_err(|err| format!("failed to set tags array: {}", err))?;
|
||||
}
|
||||
|
||||
if let Some(favorite) = meta.favorite {
|
||||
page
|
||||
.insert("favorite".to_string(), if favorite { Any::True } else { Any::False })
|
||||
.map_err(|err| format!("failed to set favorite metadata: {}", err))?;
|
||||
}
|
||||
|
||||
if let Some(trash) = meta.trash {
|
||||
page
|
||||
.insert("trash".to_string(), if trash { Any::True } else { Any::False })
|
||||
.map_err(|err| format!("failed to set trash metadata: {}", err))?;
|
||||
}
|
||||
|
||||
let now_ms = Utc::now().timestamp_millis() as f64;
|
||||
if !has_numeric_timestamp(page, "createDate") {
|
||||
page
|
||||
.insert("createDate".to_string(), Any::Float64(now_ms.into()))
|
||||
.map_err(|err| format!("failed to set createDate metadata: {}", err))?;
|
||||
}
|
||||
|
||||
page
|
||||
.insert("updatedDate".to_string(), Any::Float64(now_ms.into()))
|
||||
.map_err(|err| format!("failed to set updatedDate metadata: {}", err))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_pages_array(doc: &Doc, meta: &mut Map) -> Result<Array, String> {
|
||||
let pages_value = meta.get("pages");
|
||||
if let Some(pages) = pages_value.as_ref().and_then(|value| value.to_array()) {
|
||||
return Ok(pages);
|
||||
}
|
||||
|
||||
if let Some(Any::Array(entries)) = pages_value.and_then(|value| value.to_any()) {
|
||||
let mut pages = doc
|
||||
.create_array()
|
||||
.map_err(|err| format!("failed to create pages array: {}", err))?;
|
||||
|
||||
for entry in entries {
|
||||
let value = any_to_value(doc, entry)?;
|
||||
pages
|
||||
.push(value)
|
||||
.map_err(|err| format!("failed to migrate page entry: {}", err))?;
|
||||
}
|
||||
|
||||
meta
|
||||
.insert("pages".to_string(), Value::Array(pages.clone()))
|
||||
.map_err(|err| format!("failed to assign pages array: {}", err))?;
|
||||
|
||||
return Ok(pages);
|
||||
}
|
||||
|
||||
let pages = doc
|
||||
.create_array()
|
||||
.map_err(|err| format!("failed to create pages array: {}", err))?;
|
||||
meta
|
||||
.insert("pages".to_string(), Value::Array(pages.clone()))
|
||||
.map_err(|err| format!("failed to assign pages array: {}", err))?;
|
||||
|
||||
Ok(pages)
|
||||
}
|
||||
|
||||
fn any_to_value(doc: &Doc, any: Any) -> Result<Value, String> {
|
||||
match any {
|
||||
Any::Array(values) => {
|
||||
let mut array = doc
|
||||
.create_array()
|
||||
.map_err(|err| format!("failed to create nested array: {}", err))?;
|
||||
for value in values {
|
||||
let nested = any_to_value(doc, value)?;
|
||||
array
|
||||
.push(nested)
|
||||
.map_err(|err| format!("failed to push nested array value: {}", err))?;
|
||||
}
|
||||
Ok(Value::Array(array))
|
||||
}
|
||||
Any::Object(values) => {
|
||||
let mut map = doc
|
||||
.create_map()
|
||||
.map_err(|err| format!("failed to create nested map: {}", err))?;
|
||||
for (key, value) in *values {
|
||||
let nested = any_to_value(doc, value)?;
|
||||
map
|
||||
.insert(key, nested)
|
||||
.map_err(|err| format!("failed to insert nested map value: {}", err))?;
|
||||
}
|
||||
Ok(Value::Map(map))
|
||||
}
|
||||
_ => Ok(Value::Any(any)),
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_meta_from_page_map(page_map: &Map, doc_id: Option<String>) -> FrontmatterMeta {
|
||||
let mut meta = FrontmatterMeta {
|
||||
id: doc_id.or_else(|| get_string_from_map(page_map, "id")),
|
||||
title: get_string_from_map(page_map, "title"),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
if let Some(tags) = page_map.get("tags") {
|
||||
meta.tags = extract_tags_from_value(&tags);
|
||||
}
|
||||
|
||||
meta.favorite = page_map
|
||||
.get("favorite")
|
||||
.and_then(|value| value.to_any())
|
||||
.and_then(|value| any_to_bool(&value));
|
||||
meta.trash = page_map
|
||||
.get("trash")
|
||||
.and_then(|value| value.to_any())
|
||||
.and_then(|value| any_to_bool(&value));
|
||||
|
||||
meta
|
||||
}
|
||||
|
||||
fn extract_tags_from_value(value: &Value) -> Option<Vec<String>> {
|
||||
if let Some(array) = value.to_array() {
|
||||
let mut tags = Vec::new();
|
||||
for item in array.iter() {
|
||||
if let Some(any) = item.to_any()
|
||||
&& let Some(value) = any_to_string(&any)
|
||||
{
|
||||
tags.push(value);
|
||||
}
|
||||
}
|
||||
return Some(tags);
|
||||
}
|
||||
|
||||
value.to_any().and_then(|any| extract_tags_from_any(&any))
|
||||
}
|
||||
|
||||
fn extract_tags_from_any(value: &Any) -> Option<Vec<String>> {
|
||||
match value {
|
||||
Any::Array(values) => {
|
||||
let mut tags = Vec::new();
|
||||
for value in values {
|
||||
if let Some(tag) = any_to_string(value) {
|
||||
tags.push(tag);
|
||||
}
|
||||
}
|
||||
Some(tags)
|
||||
}
|
||||
Any::String(value) => Some(parse_tags(value)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn any_to_bool(value: &Any) -> Option<bool> {
|
||||
match value {
|
||||
Any::True => Some(true),
|
||||
Any::False => Some(false),
|
||||
Any::Integer(value) => Some(*value != 0),
|
||||
Any::BigInt64(value) => Some(*value != 0),
|
||||
Any::Float32(value) => Some(value.0 != 0.0),
|
||||
Any::Float64(value) => Some(value.0 != 0.0),
|
||||
Any::String(value) => parse_bool(value),
|
||||
Any::Null | Any::Undefined => None,
|
||||
Any::Array(_) | Any::Object(_) | Any::Binary(_) => Some(true),
|
||||
}
|
||||
}
|
||||
|
||||
fn any_to_string(value: &Any) -> Option<String> {
|
||||
match value {
|
||||
Any::String(value) => Some(value.to_string()),
|
||||
Any::Integer(value) => Some(value.to_string()),
|
||||
Any::BigInt64(value) => Some(value.to_string()),
|
||||
Any::Float32(value) => Some(value.0.to_string()),
|
||||
Any::Float64(value) => Some(value.0.to_string()),
|
||||
Any::True => Some("true".to_string()),
|
||||
Any::False => Some("false".to_string()),
|
||||
Any::Null | Any::Undefined => None,
|
||||
Any::Array(_) | Any::Object(_) | Any::Binary(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn get_string_from_map(map: &Map, key: &str) -> Option<String> {
|
||||
map.get(key).and_then(|value| {
|
||||
if let Some(text) = value.to_text() {
|
||||
return Some(text.to_string());
|
||||
}
|
||||
|
||||
value.to_any().and_then(|any| any_to_string(&any))
|
||||
})
|
||||
}
|
||||
|
||||
fn has_numeric_timestamp(page: &Map, key: &str) -> bool {
|
||||
page
|
||||
.get(key)
|
||||
.and_then(|value| value.to_any())
|
||||
.is_some_and(|value| match value {
|
||||
Any::Integer(_) | Any::BigInt64(_) => true,
|
||||
Any::Float32(value) => value.0.is_finite(),
|
||||
Any::Float64(value) => value.0.is_finite(),
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
@@ -18,7 +18,7 @@ use tokio::{sync::Mutex, task::JoinHandle};
|
||||
use super::{
|
||||
DiskDocClock, DiskDocUpdateInput, DiskSessionOptions, DiskSyncDocUpdateEvent, DiskSyncEvent,
|
||||
frontmatter::{normalize_tags, parse_frontmatter, render_frontmatter},
|
||||
root_meta::{build_root_meta_update, extract_all_root_meta, extract_root_meta_for_doc},
|
||||
root_meta::{RootMetaUpdateError, build_root_meta_update, extract_all_root_meta, extract_root_meta_for_doc},
|
||||
state_db::StateDb,
|
||||
types::{FrontmatterMeta, SourceCheckpoint},
|
||||
utils::{
|
||||
|
||||
@@ -57,6 +57,10 @@ impl DiskSession {
|
||||
self.export_root_meta_for_doc(&doc_id, &meta).await?;
|
||||
}
|
||||
|
||||
// Invalidate scan_cache so any files with deferred root metadata are
|
||||
// retried on the next scan without needing another filesystem edit.
|
||||
self.scan_cache.lock().await.files.clear();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
use super::*;
|
||||
|
||||
enum PreparedRootMetaUpdate {
|
||||
Applied(Vec<u8>, Vec<u8>),
|
||||
NoChange,
|
||||
DeferredInvalidRootShape(String),
|
||||
}
|
||||
|
||||
impl DiskSession {
|
||||
pub(crate) async fn replay_pending_updates(&self) -> Result<(), String> {
|
||||
for (doc_id, bin) in self.state_db.pending_source_updates().await? {
|
||||
@@ -48,7 +54,7 @@ impl DiskSession {
|
||||
let current = if same_update_state(&checkpoint.snapshot, local)? {
|
||||
local.to_vec()
|
||||
} else {
|
||||
merge_update_binary(Some(&checkpoint.snapshot), local)?
|
||||
merge_frontend_update_binary(Some(local), &checkpoint.snapshot)?
|
||||
};
|
||||
self.docs.lock().await.insert(doc_id.to_string(), current);
|
||||
} else {
|
||||
@@ -230,9 +236,21 @@ impl DiskSession {
|
||||
return Err(format!("markdown file changed during import: {}", file_path.display()));
|
||||
}
|
||||
|
||||
let root_update = self
|
||||
let mut next_checkpoint = next_checkpoint;
|
||||
let prepared_root = self
|
||||
.prepare_root_meta_from_file(&doc_id, &normalized_meta, existing_checkpoint.as_ref())
|
||||
.await?;
|
||||
let (root_update, deferred_root_reason) = match prepared_root {
|
||||
PreparedRootMetaUpdate::Applied(snapshot, delta) => (Some((snapshot, delta)), None),
|
||||
PreparedRootMetaUpdate::NoChange => (None, None),
|
||||
PreparedRootMetaUpdate::DeferredInvalidRootShape(reason) => {
|
||||
next_checkpoint.meta_hash = existing_checkpoint
|
||||
.as_ref()
|
||||
.map(|checkpoint| checkpoint.meta_hash.clone())
|
||||
.unwrap_or_default();
|
||||
(None, Some(reason))
|
||||
}
|
||||
};
|
||||
|
||||
let id_candidate = if has_doc_id {
|
||||
None
|
||||
@@ -307,6 +325,15 @@ impl DiskSession {
|
||||
path_bindings.insert(file_path.to_path_buf(), doc_id.clone());
|
||||
}
|
||||
|
||||
if let Some(reason) = deferred_root_reason {
|
||||
self
|
||||
.queue_error_event(format!(
|
||||
"deferred root metadata sync for {}: workspace root requires coordinated migration ({})",
|
||||
doc_id, reason
|
||||
))
|
||||
.await;
|
||||
}
|
||||
|
||||
if let Some(candidate) = id_candidate {
|
||||
self
|
||||
.queue_error_event(format!(
|
||||
@@ -325,19 +352,25 @@ impl DiskSession {
|
||||
doc_id: &str,
|
||||
meta: &FrontmatterMeta,
|
||||
baseline: Option<&SourceCheckpoint>,
|
||||
) -> Result<Option<(Vec<u8>, Vec<u8>)>, String> {
|
||||
) -> Result<PreparedRootMetaUpdate, String> {
|
||||
if !self.validate_root_meta_from_file(doc_id, meta, baseline).await? {
|
||||
return Ok(None);
|
||||
return Ok(PreparedRootMetaUpdate::NoChange);
|
||||
}
|
||||
let current_root = self.root_doc.lock().await.clone();
|
||||
let delta = build_root_meta_update(¤t_root, &self.workspace_id, doc_id, meta)?;
|
||||
let delta = match build_root_meta_update(¤t_root, &self.workspace_id, doc_id, meta) {
|
||||
Ok(delta) => delta,
|
||||
Err(RootMetaUpdateError::InvalidRootShape(reason)) => {
|
||||
return Ok(PreparedRootMetaUpdate::DeferredInvalidRootShape(reason));
|
||||
}
|
||||
Err(RootMetaUpdateError::Other(err)) => return Err(err),
|
||||
};
|
||||
|
||||
if is_empty_update(&delta) {
|
||||
return Ok(None);
|
||||
return Ok(PreparedRootMetaUpdate::NoChange);
|
||||
}
|
||||
|
||||
let merged = merge_update_binary(Some(¤t_root), &delta)?;
|
||||
Ok(Some((merged, delta)))
|
||||
Ok(PreparedRootMetaUpdate::Applied(merged, delta))
|
||||
}
|
||||
|
||||
async fn validate_root_meta_from_file(
|
||||
|
||||
@@ -1389,3 +1389,359 @@ async fn concurrent_file_and_doc_edits_require_source_reconciliation() {
|
||||
|
||||
teardown(&sync, session_id, &dir).await;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_update_state_matches_gc_compressed_snapshot_vs_incremental_stream() {
|
||||
let doc_id = "doc-gc-vs-stream";
|
||||
let base = build_full_doc("GC Test", "# GC Test\n\nhello world", doc_id).expect("build initial doc");
|
||||
let delta = update_doc(&base, "# GC Test\n\nhello affine", doc_id).expect("build edit delta");
|
||||
let stream = y_octo::merge_updates_v1([base.as_slice(), delta.as_slice()])
|
||||
.and_then(|merged| merged.encode_v1())
|
||||
.expect("merge raw incremental stream");
|
||||
|
||||
let source = affine_doc_loader::export_markdown_source(&stream, doc_id, None).expect("export source");
|
||||
let merged = affine_doc_loader::merge_markdown(affine_doc_loader::MarkdownMergeRequest {
|
||||
baseline: &stream,
|
||||
current: &stream,
|
||||
source_before: &source.markdown,
|
||||
source_after: &source.markdown,
|
||||
doc_id,
|
||||
scope: &source.scope,
|
||||
profile: source.profile,
|
||||
})
|
||||
.expect("merge markdown snapshot");
|
||||
|
||||
assert!(
|
||||
super::utils::same_update_state(&merged.snapshot, &stream)
|
||||
.expect("same_update_state should compare GC snapshot against incremental stream")
|
||||
);
|
||||
|
||||
// Also verify stepwise Y.Text items are preserved when merging with local
|
||||
// first.
|
||||
let original = hex::decode(include_str!("fixtures/stepwise-yjs.hex").replace('\n', "")).expect("decode Yjs update");
|
||||
let mut doc = DocOptions::new().build();
|
||||
doc.apply_update_from_binary_v1(&original).expect("load Yjs update");
|
||||
let reencoded = doc
|
||||
.encode_state_as_update_v1(&StateVector::default())
|
||||
.expect("re-encode Yjs update");
|
||||
let merged_frontend = super::utils::merge_frontend_update_binary(Some(&original), &reencoded)
|
||||
.expect("merge frontend update with local first");
|
||||
assert_eq!(merged_frontend, original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_update_state_returns_false_when_pending_out_of_order_updates_exist() {
|
||||
let doc = DocOptions::new().with_client_id(42).build();
|
||||
let mut text = doc.get_or_create_text("content").expect("create text");
|
||||
text.insert(0, "first").expect("insert first");
|
||||
let sv_after_first = doc.get_state_vector();
|
||||
text.insert(5, " second").expect("insert second");
|
||||
let out_of_order_delta = doc
|
||||
.encode_state_as_update_v1(&sv_after_first)
|
||||
.expect("encode second delta only");
|
||||
|
||||
let empty = DocOptions::new().build().encode_update_v1().expect("encode empty doc");
|
||||
// `out_of_order_delta` cannot integrate without the first update, so
|
||||
// `has_pending_updates()` is true even though its applied state vector and
|
||||
// delete sets match `empty`.
|
||||
let check_doc = y_octo::Doc::try_from_binary_v1(&out_of_order_delta).expect("decode out-of-order delta");
|
||||
assert!(check_doc.has_pending_updates());
|
||||
assert!(
|
||||
!super::utils::same_update_state(&out_of_order_delta, &empty)
|
||||
.expect("same_update_state should not throw on pending updates")
|
||||
);
|
||||
assert!(
|
||||
!super::utils::same_update_state(&empty, &out_of_order_delta)
|
||||
.expect("same_update_state should be symmetric for pending updates")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disk_sync_skips_root_meta_write_for_unmigrated_legacy_root_shapes() {
|
||||
use std::collections::HashMap as StdHashMap;
|
||||
|
||||
use y_octo::{AHashMap, Doc, HashMapExt};
|
||||
|
||||
// Case 1: outer `meta.pages` is a legacy `Any::Array` (2+ elements so y-octo
|
||||
// keeps Any::Array)
|
||||
let legacy_array_root = {
|
||||
let doc = Doc::default();
|
||||
let mut meta = doc.get_or_create_map("meta").expect("meta map");
|
||||
let mut page_obj: AHashMap<String, Any> = AHashMap::new();
|
||||
page_obj.insert("id".into(), Any::String("doc-existing".into()));
|
||||
page_obj.insert("title".into(), Any::String("Old Title".into()));
|
||||
let mut page_obj2: AHashMap<String, Any> = AHashMap::new();
|
||||
page_obj2.insert("id".into(), Any::String("doc-existing-2".into()));
|
||||
page_obj2.insert("title".into(), Any::String("Old Title 2".into()));
|
||||
meta
|
||||
.insert(
|
||||
"pages".into(),
|
||||
Any::Array(vec![Any::Object(Box::new(page_obj)), Any::Object(Box::new(page_obj2))]),
|
||||
)
|
||||
.expect("insert legacy Any::Array pages");
|
||||
doc.encode_update_v1().expect("encode legacy array root")
|
||||
};
|
||||
|
||||
let dir = temp_dir();
|
||||
let md_path = dir.join("doc-new-legacy.md");
|
||||
fs::write(
|
||||
&md_path,
|
||||
"---\nid: doc-new-legacy\ntitle: New Title\n---\n\n# New Title\n\nBody",
|
||||
)
|
||||
.expect("write md");
|
||||
let sync = DiskSync::new();
|
||||
let session_id = "session-legacy-array";
|
||||
let workspace_id = "ws-legacy-array";
|
||||
sync
|
||||
.start_session(
|
||||
session_id.to_string(),
|
||||
DiskSessionOptions {
|
||||
workspace_id: workspace_id.to_string(),
|
||||
sync_folder: dir.to_string_lossy().to_string(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("start session");
|
||||
let _ = sync.pull_events(session_id.to_string()).await.expect("pull discovery");
|
||||
|
||||
sync
|
||||
.prepare_source_doc(
|
||||
session_id.to_string(),
|
||||
"doc-new-legacy".to_string(),
|
||||
None,
|
||||
Some(Uint8Array::new(legacy_array_root.clone())),
|
||||
)
|
||||
.await
|
||||
.expect("prepare_source_doc should succeed and skip root meta write");
|
||||
let events = sync.pull_events(session_id.to_string()).await.expect("pull events");
|
||||
assert!(
|
||||
events
|
||||
.iter()
|
||||
.any(|e| e.update.as_ref().is_some_and(|u| u.doc_id == "doc-new-legacy")),
|
||||
"markdown doc body import must still succeed"
|
||||
);
|
||||
assert!(
|
||||
!events
|
||||
.iter()
|
||||
.any(|e| e.update.as_ref().is_some_and(|u| u.doc_id == workspace_id)),
|
||||
"disk_sync must not emit a root doc migration/meta update for legacy Any::Array"
|
||||
);
|
||||
teardown(&sync, session_id, &dir).await;
|
||||
|
||||
// Case 2: `meta.pages` is a `Y.Array` containing a legacy `Any::Object`
|
||||
// matching target doc_id
|
||||
let legacy_mixed_root = {
|
||||
let doc = Doc::default();
|
||||
let mut meta = doc.get_or_create_map("meta").expect("meta map");
|
||||
let mut pages = doc.create_array().expect("pages array");
|
||||
let mut page_obj: AHashMap<String, Any> = AHashMap::new();
|
||||
page_obj.insert("id".into(), Any::String("doc-mixed".into()));
|
||||
page_obj.insert("title".into(), Any::String("Old Mixed".into()));
|
||||
pages
|
||||
.push(Value::Any(Any::Object(Box::new(page_obj))))
|
||||
.expect("push legacy object");
|
||||
meta
|
||||
.insert("pages".into(), Value::Array(pages))
|
||||
.expect("insert mixed pages");
|
||||
doc.encode_update_v1().expect("encode mixed root")
|
||||
};
|
||||
|
||||
let err = build_root_meta_update(
|
||||
&legacy_mixed_root,
|
||||
"ws-mixed",
|
||||
"doc-mixed",
|
||||
&FrontmatterMeta {
|
||||
id: Some("doc-mixed".into()),
|
||||
title: Some("Updated Mixed".into()),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.expect_err("mixed Y.Array hitting legacy Any::Object must return InvalidRootShape");
|
||||
assert!(matches!(
|
||||
err,
|
||||
super::root_meta::RootMetaUpdateError::InvalidRootShape(_)
|
||||
));
|
||||
|
||||
// Verify no duplicate page IDs exist when reading back
|
||||
let extracted = affine_doc_loader::extract_all_root_meta(&legacy_mixed_root).expect("extract meta");
|
||||
let mut counts: StdHashMap<String, usize> = StdHashMap::new();
|
||||
for page in extracted {
|
||||
*counts.entry(page.id).or_default() += 1;
|
||||
}
|
||||
assert_eq!(counts.get("doc-mixed"), Some(&1));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disk_sync_retries_deferred_root_meta_after_server_migration() {
|
||||
use y_octo::{AHashMap, Doc, HashMapExt};
|
||||
|
||||
let doc_id = "doc-deferred-meta";
|
||||
let workspace_id = "ws-deferred-meta";
|
||||
let session_id = "session-deferred-meta";
|
||||
|
||||
// Build a legacy Any::Array root doc containing `doc-deferred-meta` (2+
|
||||
// elements so y-octo keeps Any::Array)
|
||||
let legacy_array_root = {
|
||||
let doc = Doc::default();
|
||||
let mut meta = doc.get_or_create_map("meta").expect("meta map");
|
||||
let mut page_obj: AHashMap<String, Any> = AHashMap::new();
|
||||
page_obj.insert("id".into(), Any::String(doc_id.into()));
|
||||
page_obj.insert("title".into(), Any::String("Deferred Title".into()));
|
||||
let mut peer_page: AHashMap<String, Any> = AHashMap::new();
|
||||
peer_page.insert("id".into(), Any::String("doc-deferred-peer".into()));
|
||||
peer_page.insert("title".into(), Any::String("Peer Title".into()));
|
||||
meta
|
||||
.insert(
|
||||
"pages".into(),
|
||||
Any::Array(vec![Any::Object(Box::new(page_obj)), Any::Object(Box::new(peer_page))]),
|
||||
)
|
||||
.expect("insert legacy Any::Array pages");
|
||||
doc.encode_update_v1().expect("encode legacy array root")
|
||||
};
|
||||
|
||||
let initial_doc = build_full_doc("Deferred Title", "# Deferred Title\n\nBody", doc_id).expect("build doc");
|
||||
|
||||
let dir = temp_dir();
|
||||
let sync = DiskSync::new();
|
||||
sync
|
||||
.start_session(
|
||||
session_id.to_string(),
|
||||
DiskSessionOptions {
|
||||
workspace_id: workspace_id.to_string(),
|
||||
sync_folder: dir.to_string_lossy().to_string(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("start session");
|
||||
|
||||
// Seed legacy root doc and initial page doc into session
|
||||
sync
|
||||
.apply_local_update(
|
||||
session_id.to_string(),
|
||||
DiskDocUpdateInput {
|
||||
doc_id: workspace_id.to_string(),
|
||||
bin: Uint8Array::new(legacy_array_root.clone()),
|
||||
editor: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("apply legacy root");
|
||||
sync
|
||||
.apply_local_update(
|
||||
session_id.to_string(),
|
||||
DiskDocUpdateInput {
|
||||
doc_id: doc_id.to_string(),
|
||||
bin: Uint8Array::new(initial_doc.clone()),
|
||||
editor: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("apply initial doc");
|
||||
let _ = sync.pull_events(session_id.to_string()).await.expect("drain initial");
|
||||
|
||||
// Locate exported markdown file and edit frontmatter tags
|
||||
let md_path = fs::read_dir(&dir)
|
||||
.expect("read dir")
|
||||
.filter_map(|e| e.ok().map(|e| e.path()))
|
||||
.find(|p| p.extension().and_then(|s| s.to_str()) == Some("md"))
|
||||
.expect("exported markdown file");
|
||||
let original_md = fs::read_to_string(&md_path).expect("read exported md");
|
||||
let updated_md = original_md.replacen("tags: []", "tags:\n - deferred-tag", 1);
|
||||
assert_ne!(original_md, updated_md, "tags line must exist in exported frontmatter");
|
||||
fs::write(&md_path, &updated_md).expect("write updated md");
|
||||
|
||||
// Discover edited file and prepare source doc: skips root meta write,
|
||||
// preserves retryable meta_hash, emits deferred error event
|
||||
let discovered = sync.pull_events(session_id.to_string()).await.expect("discover edit");
|
||||
assert!(
|
||||
discovered
|
||||
.iter()
|
||||
.any(|e| e.r#type == "source-discovered" && e.doc_id.as_deref() == Some(doc_id))
|
||||
);
|
||||
sync
|
||||
.prepare_source_doc(
|
||||
session_id.to_string(),
|
||||
doc_id.to_string(),
|
||||
Some(Uint8Array::new(initial_doc.clone())),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.expect("prepare_source_doc should defer root meta write");
|
||||
let events_first = sync.pull_events(session_id.to_string()).await.expect("first scan");
|
||||
assert!(
|
||||
!events_first
|
||||
.iter()
|
||||
.any(|e| e.update.as_ref().is_some_and(|u| u.doc_id == workspace_id)),
|
||||
"must not emit root doc update while root is still legacy Any::Array"
|
||||
);
|
||||
assert!(
|
||||
events_first.iter().any(|e| {
|
||||
e.r#type == "error"
|
||||
&& e
|
||||
.message
|
||||
.as_deref()
|
||||
.is_some_and(|m| m.contains("deferred root metadata sync"))
|
||||
}),
|
||||
"must emit observable deferred root metadata sync error event"
|
||||
);
|
||||
|
||||
// Simulate server-side coordinated migration of root doc
|
||||
// (`migrate_root_doc_pages`)
|
||||
let migration_delta = affine_doc_loader::migrate_root_doc_pages(&legacy_array_root)
|
||||
.expect("migrate legacy root")
|
||||
.expect("migration delta");
|
||||
sync
|
||||
.apply_local_update(
|
||||
session_id.to_string(),
|
||||
DiskDocUpdateInput {
|
||||
doc_id: workspace_id.to_string(),
|
||||
bin: Uint8Array::new(migration_delta.clone()),
|
||||
editor: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("apply migrated root update");
|
||||
|
||||
// Second scan without touching the markdown file: untouched file is
|
||||
// re-discovered because meta_hash was not advanced, and preparing it writes
|
||||
// tags to the migrated root doc
|
||||
let rediscovered = sync.pull_events(session_id.to_string()).await.expect("second scan");
|
||||
assert!(
|
||||
rediscovered
|
||||
.iter()
|
||||
.any(|e| e.r#type == "source-discovered" && e.doc_id.as_deref() == Some(doc_id)),
|
||||
"untouched file with deferred root metadata must be re-discovered after migration"
|
||||
);
|
||||
sync
|
||||
.prepare_source_doc(
|
||||
session_id.to_string(),
|
||||
doc_id.to_string(),
|
||||
Some(Uint8Array::new(initial_doc)),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.expect("prepare_source_doc after migration should write root meta");
|
||||
let events_second = sync.pull_events(session_id.to_string()).await.expect("after prepare");
|
||||
let root_update_event = events_second
|
||||
.iter()
|
||||
.find_map(|e| e.update.as_ref().filter(|u| u.doc_id == workspace_id))
|
||||
.expect("second scan must emit root meta update after migration");
|
||||
let migrated_root =
|
||||
super::utils::merge_update_binary(Some(&legacy_array_root), &migration_delta).expect("merge migration");
|
||||
let final_root = super::utils::merge_update_binary(Some(&migrated_root), root_update_event.bin.as_ref())
|
||||
.expect("merge root meta update");
|
||||
let final_meta = super::root_meta::extract_root_meta_for_doc(&final_root, doc_id)
|
||||
.expect("extract final root meta")
|
||||
.expect("doc meta present");
|
||||
assert_eq!(final_meta.tags, Some(vec!["deferred-tag".to_string()]));
|
||||
|
||||
// Third scan: stable with no redundant events
|
||||
let events_third = sync.pull_events(session_id.to_string()).await.expect("third scan");
|
||||
assert!(
|
||||
events_third.is_empty(),
|
||||
"subsequent scan should be stable with no redundant events, got: {:?}",
|
||||
events_third.iter().map(|e| (&e.r#type, &e.message)).collect::<Vec<_>>()
|
||||
);
|
||||
|
||||
teardown(&sync, session_id, &dir).await;
|
||||
}
|
||||
@@ -7,7 +7,7 @@ use std::{
|
||||
use chrono::{DateTime, NaiveDateTime, Utc};
|
||||
use sha3::{Digest, Sha3_256};
|
||||
use uuid::Uuid;
|
||||
use y_octo::{Doc, DocOptions, merge_updates_v1};
|
||||
use y_octo::{Doc, merge_updates_v1, validate_update_v1};
|
||||
|
||||
use super::{frontmatter::normalize_tags, types::FrontmatterMeta};
|
||||
|
||||
@@ -225,8 +225,14 @@ pub(crate) fn merge_frontend_update_binary(existing: Option<&[u8]>, update: &[u8
|
||||
}
|
||||
|
||||
pub(crate) fn same_update_state(left: &[u8], right: &[u8]) -> Result<bool, String> {
|
||||
if left == right && (is_empty_update(left) || validate_update_v1(left).is_ok()) {
|
||||
return Ok(true);
|
||||
}
|
||||
let left_doc = Doc::try_from_binary_v1(left).map_err(|err| format!("failed to decode checkpoint update: {err}"))?;
|
||||
let right_doc = Doc::try_from_binary_v1(right).map_err(|err| format!("failed to decode local update: {err}"))?;
|
||||
if left_doc.has_pending_updates() || right_doc.has_pending_updates() {
|
||||
return Ok(false);
|
||||
}
|
||||
Ok(
|
||||
left_doc.get_state_vector() == right_doc.get_state_vector()
|
||||
&& left_doc.get_delete_sets() == right_doc.get_delete_sets(),
|
||||
@@ -245,17 +251,6 @@ pub(crate) fn merge_root_update_binary(existing: &[u8], update: &[u8]) -> Result
|
||||
.map_err(|err| format!("failed to merge root update: {err}"))
|
||||
}
|
||||
|
||||
pub(crate) fn load_doc_or_new(binary: &[u8], doc_id: Option<&str>) -> Result<Doc, String> {
|
||||
let options = match doc_id {
|
||||
Some(id) => DocOptions::new().with_guid(id.to_owned()),
|
||||
None => DocOptions::new(),
|
||||
};
|
||||
if is_empty_update(binary) {
|
||||
return Ok(options.build());
|
||||
}
|
||||
Doc::try_from_binary_v1_with_options(binary, options).map_err(|err| format!("failed to decode doc binary: {err}"))
|
||||
}
|
||||
|
||||
pub(crate) fn paths_equal(lhs: &Path, rhs: &Path) -> bool {
|
||||
if lhs == rhs {
|
||||
return true;
|
||||
|
||||
@@ -3,6 +3,7 @@ pub mod hashcash;
|
||||
mod import;
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
pub mod preview;
|
||||
pub mod workspace_meta;
|
||||
|
||||
#[cfg(not(target_arch = "arm"))]
|
||||
#[global_allocator]
|
||||
@@ -14,3 +15,4 @@ pub use affine_nbstore::*;
|
||||
pub use affine_sqlite_v1::*;
|
||||
pub use disk_sync::*;
|
||||
pub use import::*;
|
||||
pub use workspace_meta::*;
|
||||
@@ -0,0 +1,534 @@
|
||||
use std::borrow::Cow;
|
||||
|
||||
use napi::{Status, bindgen_prelude::Uint8Array};
|
||||
use napi_derive::napi;
|
||||
use y_octo::{
|
||||
Any, DocOptions, DocSession, ReadDoc, ReadError, ReadLimits, ReadValue, SessionConfig, SessionReadValue,
|
||||
SessionUndoConfig, TypeIdentity, TypeTarget,
|
||||
};
|
||||
|
||||
#[napi(object)]
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct WorkspaceRootDocMeta {
|
||||
pub name: Option<String>,
|
||||
pub avatar: Option<String>,
|
||||
pub page_count: Option<u32>,
|
||||
}
|
||||
|
||||
fn generic_err(err: impl std::fmt::Display) -> napi::Error {
|
||||
napi::Error::new(Status::GenericFailure, err.to_string())
|
||||
}
|
||||
|
||||
fn is_empty_update(update: &[u8]) -> bool {
|
||||
update.is_empty() || update == [0, 0]
|
||||
}
|
||||
|
||||
fn merge_non_empty_updates<'a>(updates: &[&'a [u8]]) -> napi::Result<Option<Cow<'a, [u8]>>> {
|
||||
let non_empty: Vec<&[u8]> = updates.iter().copied().filter(|u| !is_empty_update(u)).collect();
|
||||
match non_empty.as_slice() {
|
||||
[] => Ok(None),
|
||||
[single] => Ok(Some(Cow::Borrowed(*single))),
|
||||
many => {
|
||||
let merged = y_octo::merge_updates_v1(many).map_err(generic_err)?;
|
||||
let encoded = merged.encode_v1().map_err(generic_err)?;
|
||||
Ok(Some(Cow::Owned(encoded)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_ambiguous_json_string(s: &str) -> bool {
|
||||
let trimmed = s.trim();
|
||||
trimmed.starts_with('"')
|
||||
|| trimmed.starts_with('[')
|
||||
|| trimmed.starts_with('{')
|
||||
|| matches!(trimmed, "null" | "true" | "false")
|
||||
|| trimmed
|
||||
.as_bytes()
|
||||
.first()
|
||||
.is_some_and(|b| *b == b'-' || b.is_ascii_digit())
|
||||
}
|
||||
|
||||
enum FastField<T> {
|
||||
Resolved(Option<T>),
|
||||
Ambiguous,
|
||||
}
|
||||
|
||||
fn read_fast_string(value: Option<ReadValue<'_>>) -> FastField<String> {
|
||||
match value {
|
||||
None => FastField::Resolved(None),
|
||||
Some(ReadValue::Any(any)) => {
|
||||
if let Some(s) = any.as_str() {
|
||||
if is_ambiguous_json_string(s) {
|
||||
FastField::Ambiguous
|
||||
} else {
|
||||
FastField::Resolved(Some(s.to_owned()))
|
||||
}
|
||||
} else if any.array().is_some() {
|
||||
FastField::Ambiguous
|
||||
} else {
|
||||
FastField::Resolved(None)
|
||||
}
|
||||
}
|
||||
Some(_) => FastField::Resolved(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_fast_page_count(value: Option<ReadValue<'_>>) -> FastField<u32> {
|
||||
match value {
|
||||
None => FastField::Resolved(None),
|
||||
Some(ReadValue::Array(arr)) => FastField::Resolved(Some(u32::try_from(arr.len()).unwrap_or(u32::MAX))),
|
||||
Some(ReadValue::Any(any)) => {
|
||||
if let Some(iter) = any.array() {
|
||||
let mut count: usize = 0;
|
||||
for item in iter {
|
||||
if item.as_str().is_some_and(is_ambiguous_json_string) {
|
||||
return FastField::Ambiguous;
|
||||
}
|
||||
count += 1;
|
||||
}
|
||||
FastField::Resolved(Some(u32::try_from(count).unwrap_or(u32::MAX)))
|
||||
} else {
|
||||
FastField::Ambiguous
|
||||
}
|
||||
}
|
||||
Some(_) => FastField::Resolved(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_meta_via_session(bytes: &[u8]) -> napi::Result<WorkspaceRootDocMeta> {
|
||||
let session = DocSession::<()>::from_update_v1(
|
||||
bytes,
|
||||
DocOptions::from_identity(1, "meta".into()),
|
||||
SessionConfig {
|
||||
undo: SessionUndoConfig::Disabled,
|
||||
},
|
||||
)
|
||||
.map_err(generic_err)?;
|
||||
|
||||
let meta_id = TypeIdentity::Root("meta".into());
|
||||
if !session.type_status(&meta_id).alive {
|
||||
return Ok(WorkspaceRootDocMeta::default());
|
||||
}
|
||||
|
||||
let meta_target = TypeTarget::Identity(meta_id);
|
||||
let name = match session.get_map_value(&meta_target, "name").map_err(generic_err)? {
|
||||
Some(SessionReadValue::Any(Any::String(s))) => Some(s),
|
||||
_ => None,
|
||||
};
|
||||
let avatar = match session.get_map_value(&meta_target, "avatar").map_err(generic_err)? {
|
||||
Some(SessionReadValue::Any(Any::String(s))) => Some(s),
|
||||
_ => None,
|
||||
};
|
||||
let page_count = match session.get_map_value(&meta_target, "pages").map_err(generic_err)? {
|
||||
Some(SessionReadValue::Array(id)) => {
|
||||
let len = session.read_array(&id.into()).map_err(generic_err)?.len();
|
||||
Some(u32::try_from(len).unwrap_or(u32::MAX))
|
||||
}
|
||||
Some(SessionReadValue::Any(Any::Array(arr))) => Some(u32::try_from(arr.len()).unwrap_or(u32::MAX)),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
Ok(WorkspaceRootDocMeta {
|
||||
name,
|
||||
avatar,
|
||||
page_count,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_workspace_root_doc_meta_slices(updates: &[&[u8]]) -> napi::Result<WorkspaceRootDocMeta> {
|
||||
let Some(merged) = merge_non_empty_updates(updates)? else {
|
||||
return Ok(WorkspaceRootDocMeta::default());
|
||||
};
|
||||
|
||||
match ReadDoc::from_full_update_v1_with_limits(merged.as_ref(), ReadLimits::default()) {
|
||||
Ok(read_doc) => {
|
||||
let Some(meta) = read_doc.map("meta") else {
|
||||
return Ok(WorkspaceRootDocMeta::default());
|
||||
};
|
||||
|
||||
let name = match read_fast_string(meta.get("name")) {
|
||||
FastField::Resolved(v) => v,
|
||||
FastField::Ambiguous => return read_meta_via_session(merged.as_ref()),
|
||||
};
|
||||
let avatar = match read_fast_string(meta.get("avatar")) {
|
||||
FastField::Resolved(v) => v,
|
||||
FastField::Ambiguous => return read_meta_via_session(merged.as_ref()),
|
||||
};
|
||||
let page_count = match read_fast_page_count(meta.get("pages")) {
|
||||
FastField::Resolved(v) => v,
|
||||
FastField::Ambiguous => return read_meta_via_session(merged.as_ref()),
|
||||
};
|
||||
|
||||
Ok(WorkspaceRootDocMeta {
|
||||
name,
|
||||
avatar,
|
||||
page_count,
|
||||
})
|
||||
}
|
||||
Err(ReadError::IncompleteSnapshot(_)) => read_meta_via_session(merged.as_ref()),
|
||||
Err(err) => Err(generic_err(err)),
|
||||
}
|
||||
}
|
||||
|
||||
fn compact_doc_updates_v1_with_limits(updates: &[&[u8]], limits: ReadLimits) -> napi::Result<Vec<u8>> {
|
||||
let non_empty: Vec<&[u8]> = updates.iter().copied().filter(|u| !is_empty_update(u)).collect();
|
||||
let merged: Cow<'_, [u8]> = match non_empty.as_slice() {
|
||||
[] => return Ok(vec![0, 0]),
|
||||
[single] => {
|
||||
y_octo::validate_update_v1(single).map_err(generic_err)?;
|
||||
Cow::Borrowed(*single)
|
||||
}
|
||||
many => {
|
||||
let merged = y_octo::merge_updates_v1(many).map_err(generic_err)?;
|
||||
Cow::Owned(merged.encode_v1().map_err(generic_err)?)
|
||||
}
|
||||
};
|
||||
|
||||
match ReadDoc::from_full_update_v1_with_limits(merged.as_ref(), limits) {
|
||||
Ok(_) => {
|
||||
let mut doc = DocOptions::new().build();
|
||||
doc.apply_update_from_binary_v1(merged.as_ref()).map_err(generic_err)?;
|
||||
doc.gc().map_err(generic_err)?;
|
||||
doc.encode_update_v1().map_err(generic_err)
|
||||
}
|
||||
Err(ReadError::IncompleteSnapshot(_) | ReadError::ResourceLimit(_)) => Ok(merged.into_owned()),
|
||||
Err(ReadError::InvalidUpdate(err)) => Err(generic_err(err)),
|
||||
}
|
||||
}
|
||||
|
||||
fn compact_doc_updates_v1_slices(updates: &[&[u8]]) -> napi::Result<Vec<u8>> {
|
||||
compact_doc_updates_v1_with_limits(updates, ReadLimits::default())
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub fn parse_workspace_root_doc_meta(updates: Vec<Uint8Array>) -> napi::Result<WorkspaceRootDocMeta> {
|
||||
let slices: Vec<&[u8]> = updates.iter().map(|u| u.as_ref()).collect();
|
||||
parse_workspace_root_doc_meta_slices(&slices)
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub fn compact_doc_updates_v1(updates: Vec<Uint8Array>) -> napi::Result<Uint8Array> {
|
||||
let slices: Vec<&[u8]> = updates.iter().map(|u| u.as_ref()).collect();
|
||||
Ok(Uint8Array::new(compact_doc_updates_v1_slices(&slices)?))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use y_octo::{AHashMap, CrdtWriter, RawEncoder, StateVector, Value};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn page_entry(id: &str) -> Any {
|
||||
Any::Object(Box::new(AHashMap::from_iter([(
|
||||
"id".to_string(),
|
||||
Any::String(id.to_string()),
|
||||
)])))
|
||||
}
|
||||
|
||||
fn encode_legacy_content_json_meta(entries: &[(&str, &str)]) -> Vec<u8> {
|
||||
let mut enc = RawEncoder::default();
|
||||
// 1 client
|
||||
enc.write_var_u64(1).unwrap();
|
||||
// N structs for client 1 starting at clock 0
|
||||
enc.write_var_u64(entries.len() as u64).unwrap();
|
||||
enc.write_var_u64(1).unwrap();
|
||||
enc.write_var_u64(0).unwrap();
|
||||
|
||||
for (key, json_elem) in entries {
|
||||
// info = ITEM_HAS_PARENT_SUB (0x20) | Content::Json (2)
|
||||
enc.write_u8(0x20 | 2).unwrap();
|
||||
// named root
|
||||
enc.write_u8(1).unwrap();
|
||||
enc.write_var_string("meta").unwrap();
|
||||
enc.write_var_string(key).unwrap();
|
||||
enc.write_var_u64(1).unwrap();
|
||||
enc.write_var_string(json_elem).unwrap();
|
||||
}
|
||||
|
||||
// Empty delete set
|
||||
enc.write_var_u64(0).unwrap();
|
||||
enc.into_inner()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_y_array_pages_and_avatar() {
|
||||
let doc = DocOptions::new().with_client_id(1).build();
|
||||
let mut meta = doc.get_or_create_map("meta").unwrap();
|
||||
meta.insert("name".to_string(), "My Workspace").unwrap();
|
||||
meta.insert("avatar".to_string(), "avatar-key").unwrap();
|
||||
|
||||
let mut pages = doc.create_array().unwrap();
|
||||
pages.push(page_entry("page-1")).unwrap();
|
||||
pages.push(page_entry("page-2")).unwrap();
|
||||
meta.insert("pages".to_string(), pages).unwrap();
|
||||
|
||||
let update = doc.encode_update_v1().unwrap();
|
||||
let parsed = parse_workspace_root_doc_meta_slices(&[&update]).unwrap();
|
||||
assert_eq!(
|
||||
parsed,
|
||||
WorkspaceRootDocMeta {
|
||||
name: Some("My Workspace".to_string()),
|
||||
avatar: Some("avatar-key".to_string()),
|
||||
page_count: Some(2),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_any_array_pages_and_incremental_name_override() {
|
||||
let doc = DocOptions::new().with_client_id(1).build();
|
||||
let mut meta = doc.get_or_create_map("meta").unwrap();
|
||||
meta.insert("name".to_string(), "Before").unwrap();
|
||||
// Yjs `meta.set('pages', [{ id: 'page-a' }])` writes a 1-element ContentAny
|
||||
// whose single item is Any::Array.
|
||||
meta
|
||||
.insert(
|
||||
"pages".to_string(),
|
||||
Any::Array(vec![Any::Array(vec![page_entry("page-a")])]),
|
||||
)
|
||||
.unwrap();
|
||||
let first = doc.encode_update_v1().unwrap();
|
||||
let sv = doc.get_state_vector();
|
||||
|
||||
meta.insert("name".to_string(), "After").unwrap();
|
||||
let second = doc.encode_state_as_update_v1(&sv).unwrap();
|
||||
|
||||
let parsed = parse_workspace_root_doc_meta_slices(&[&[], &first, &second]).unwrap();
|
||||
assert_eq!(
|
||||
parsed,
|
||||
WorkspaceRootDocMeta {
|
||||
name: Some("After".to_string()),
|
||||
avatar: None,
|
||||
page_count: Some(1),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_legacy_content_json_root_meta() {
|
||||
let bytes = encode_legacy_content_json_meta(&[
|
||||
("name", "\"Test\""),
|
||||
("avatar", "\"img\""),
|
||||
("pages", "[{\"id\":\"1\"},{\"id\":\"2\"}]"),
|
||||
]);
|
||||
|
||||
let parsed = parse_workspace_root_doc_meta_slices(&[&bytes]).unwrap();
|
||||
assert_eq!(
|
||||
parsed,
|
||||
WorkspaceRootDocMeta {
|
||||
name: Some("Test".to_string()),
|
||||
avatar: Some("img".to_string()),
|
||||
page_count: Some(2),
|
||||
}
|
||||
);
|
||||
|
||||
// Legacy Content::Json numeric literal ("123") decodes as integer, so
|
||||
// `name` / `avatar` must be None.
|
||||
let numeric_json = encode_legacy_content_json_meta(&[("name", "123"), ("avatar", "-42")]);
|
||||
assert_eq!(
|
||||
parse_workspace_root_doc_meta_slices(&[&numeric_json]).unwrap(),
|
||||
WorkspaceRootDocMeta::default()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_quoted_modern_any_string_name() {
|
||||
let doc = DocOptions::new().with_client_id(1).build();
|
||||
let mut meta = doc.get_or_create_map("meta").unwrap();
|
||||
meta.insert("name".to_string(), "\"Quoted\"").unwrap();
|
||||
meta.insert("avatar".to_string(), "123").unwrap();
|
||||
let mut pages = doc.create_array().unwrap();
|
||||
pages.push(page_entry("page-1")).unwrap();
|
||||
meta.insert("pages".to_string(), pages).unwrap();
|
||||
|
||||
let update = doc.encode_update_v1().unwrap();
|
||||
let parsed = parse_workspace_root_doc_meta_slices(&[&update]).unwrap();
|
||||
assert_eq!(
|
||||
parsed,
|
||||
WorkspaceRootDocMeta {
|
||||
name: Some("\"Quoted\"".to_string()),
|
||||
avatar: Some("123".to_string()),
|
||||
page_count: Some(1),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn falls_back_to_session_on_incomplete_snapshot() {
|
||||
let doc = DocOptions::new().with_client_id(1).build();
|
||||
let mut meta = doc.get_or_create_map("meta").unwrap();
|
||||
meta.insert("name".to_string(), "Arrived").unwrap();
|
||||
let mut pages = doc.create_array().unwrap();
|
||||
pages.push(page_entry("page-1")).unwrap();
|
||||
meta.insert("pages".to_string(), pages).unwrap();
|
||||
let arrived_meta = doc.encode_update_v1().unwrap();
|
||||
|
||||
// Create a second client with a clock gap so ReadDoc returns
|
||||
// IncompleteSnapshot.
|
||||
let peer = DocOptions::new().with_client_id(2).build();
|
||||
let mut text = peer.get_or_create_text("notes").unwrap();
|
||||
text.insert(0, "first").unwrap();
|
||||
let sv_after_first = peer.get_state_vector();
|
||||
text.insert(5, "second").unwrap();
|
||||
let pending_tail = peer.encode_state_as_update_v1(&sv_after_first).unwrap();
|
||||
|
||||
let parsed = parse_workspace_root_doc_meta_slices(&[&arrived_meta, &pending_tail]).unwrap();
|
||||
assert_eq!(
|
||||
parsed,
|
||||
WorkspaceRootDocMeta {
|
||||
name: Some("Arrived".to_string()),
|
||||
avatar: None,
|
||||
page_count: Some(1),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_pages_or_meta_returns_none() {
|
||||
let doc = DocOptions::new().with_client_id(1).build();
|
||||
let mut meta = doc.get_or_create_map("meta").unwrap();
|
||||
meta.insert("name".to_string(), "No Pages").unwrap();
|
||||
let update = doc.encode_update_v1().unwrap();
|
||||
|
||||
let parsed = parse_workspace_root_doc_meta_slices(&[&update]).unwrap();
|
||||
assert_eq!(
|
||||
parsed,
|
||||
WorkspaceRootDocMeta {
|
||||
name: Some("No Pages".to_string()),
|
||||
avatar: None,
|
||||
page_count: None,
|
||||
}
|
||||
);
|
||||
|
||||
let empty = parse_workspace_root_doc_meta_slices(&[]).unwrap();
|
||||
assert_eq!(empty, WorkspaceRootDocMeta::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_update_returns_generic_failure() {
|
||||
let err = parse_workspace_root_doc_meta_slices(&[&[0u8]]).unwrap_err();
|
||||
assert_eq!(err.status, Status::GenericFailure);
|
||||
|
||||
let compact_err = compact_doc_updates_v1_slices(&[&[0u8]]).unwrap_err();
|
||||
assert_eq!(compact_err.status, Status::GenericFailure);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compact_doc_updates_v1_reclaims_deleted_payloads() {
|
||||
let doc = DocOptions::new().with_client_id(17).build();
|
||||
let mut text = doc.get_or_create_text("body").unwrap();
|
||||
let payload = "x".repeat(64 * 1024);
|
||||
let mut updates = Vec::new();
|
||||
let mut sv = StateVector::default();
|
||||
|
||||
for _ in 0..4 {
|
||||
text.insert(0, &payload).unwrap();
|
||||
let ins = doc.encode_state_as_update_v1(&sv).unwrap();
|
||||
sv = doc.get_state_vector();
|
||||
updates.push(ins);
|
||||
|
||||
text.remove(0, payload.len() as u64).unwrap();
|
||||
let del = doc.encode_state_as_update_v1(&sv).unwrap();
|
||||
sv = doc.get_state_vector();
|
||||
updates.push(del);
|
||||
}
|
||||
|
||||
let slices: Vec<&[u8]> = updates.iter().map(Vec::as_slice).collect();
|
||||
let compacted = compact_doc_updates_v1_slices(&slices).unwrap();
|
||||
assert!(
|
||||
compacted.len() < 64,
|
||||
"expected compacted bytes < 64, got {}",
|
||||
compacted.len()
|
||||
);
|
||||
|
||||
let mut reopened = DocOptions::new().with_client_id(99).build();
|
||||
reopened.apply_update_from_binary_v1(&compacted).unwrap();
|
||||
assert_eq!(reopened.get_or_create_text("body").unwrap().to_string(), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compact_doc_updates_v1_preserves_pending_updates_until_complete() {
|
||||
let author = DocOptions::new().with_client_id(21).build();
|
||||
let mut text = author.get_or_create_text("body").unwrap();
|
||||
text.insert(0, "hello").unwrap();
|
||||
let u1 = author.encode_update_v1().unwrap();
|
||||
let sv1 = author.get_state_vector();
|
||||
|
||||
text.insert(5, " world").unwrap();
|
||||
let u2 = author.encode_state_as_update_v1(&sv1).unwrap();
|
||||
let sv2 = author.get_state_vector();
|
||||
|
||||
let big = "z".repeat(16 * 1024);
|
||||
text.insert(11, &big).unwrap();
|
||||
let u3 = author.encode_state_as_update_v1(&sv2).unwrap();
|
||||
let sv3 = author.get_state_vector();
|
||||
|
||||
text.remove(11, big.len() as u64).unwrap();
|
||||
let u4 = author.encode_state_as_update_v1(&sv3).unwrap();
|
||||
|
||||
// Compact out-of-order updates (missing u1): must keep pending structs
|
||||
// intact.
|
||||
let pending_compacted = compact_doc_updates_v1_slices(&[&u2, &u3, &u4]).unwrap();
|
||||
|
||||
// Once u1 arrives, compact again: full text converges and deleted 16 KiB is
|
||||
// reclaimed.
|
||||
let final_compacted = compact_doc_updates_v1_slices(&[&pending_compacted, &u1]).unwrap();
|
||||
assert!(
|
||||
final_compacted.len() < 128,
|
||||
"expected final compacted bytes < 128, got {}",
|
||||
final_compacted.len()
|
||||
);
|
||||
|
||||
let mut reopened = DocOptions::new().with_client_id(99).build();
|
||||
reopened.apply_update_from_binary_v1(&final_compacted).unwrap();
|
||||
assert_eq!(reopened.get_or_create_text("body").unwrap().to_string(), "hello world");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compact_doc_updates_v1_skips_gc_on_resource_limit_without_losing_data() {
|
||||
let doc1 = DocOptions::new().with_client_id(1).build();
|
||||
doc1
|
||||
.get_or_create_map("data")
|
||||
.unwrap()
|
||||
.insert("v".to_string(), 1i64)
|
||||
.unwrap();
|
||||
let u1 = doc1.encode_update_v1().unwrap();
|
||||
|
||||
let mut doc2 = DocOptions::new().with_client_id(2).build();
|
||||
doc2.apply_update_from_binary_v1(&u1).unwrap();
|
||||
doc2
|
||||
.get_or_create_map("data")
|
||||
.unwrap()
|
||||
.insert("v".to_string(), 2i64)
|
||||
.unwrap();
|
||||
let snapshot = doc2.encode_update_v1().unwrap();
|
||||
|
||||
let mut doc3 = DocOptions::new().with_client_id(3).build();
|
||||
doc3.apply_update_from_binary_v1(&snapshot).unwrap();
|
||||
let sv2 = doc3.get_state_vector();
|
||||
doc3
|
||||
.get_or_create_map("data")
|
||||
.unwrap()
|
||||
.insert("v".to_string(), 3i64)
|
||||
.unwrap();
|
||||
let update = doc3.encode_state_as_update_v1(&sv2).unwrap();
|
||||
let expected_sv = doc3.get_state_vector();
|
||||
|
||||
let limits = ReadLimits {
|
||||
max_clients: 2,
|
||||
..ReadLimits::default()
|
||||
};
|
||||
let compacted = compact_doc_updates_v1_with_limits(&[&snapshot, &update], limits.clone()).unwrap();
|
||||
|
||||
let mut reopened = DocOptions::new().with_client_id(99).build();
|
||||
reopened.apply_update_from_binary_v1(&compacted).unwrap();
|
||||
assert_eq!(
|
||||
reopened.get_map("data").unwrap().get("v"),
|
||||
Some(Value::Any(Any::from(3i64)))
|
||||
);
|
||||
assert_eq!(reopened.get_state_vector(), expected_sv);
|
||||
|
||||
let err = compact_doc_updates_v1_with_limits(&[&[0u8]], limits).unwrap_err();
|
||||
assert_eq!(err.status, Status::GenericFailure);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,6 @@
|
||||
import { readFileSync, writeFileSync } from 'node:fs';
|
||||
|
||||
import {
|
||||
applyUpdate,
|
||||
Doc,
|
||||
encodeStateAsUpdate,
|
||||
encodeStateVector,
|
||||
UndoManager,
|
||||
} from 'yjs';
|
||||
import serverNative from '@affine/server-native';
|
||||
|
||||
type InputFormat = 'file' | 'base64' | 'hex';
|
||||
type OutputFormat = 'bin' | 'base64' | 'hex';
|
||||
@@ -35,21 +29,12 @@ function generateRevertUpdate(
|
||||
fromNewerBin: Uint8Array,
|
||||
toOlderBin: Uint8Array
|
||||
): Uint8Array {
|
||||
const newerDoc = new Doc();
|
||||
applyUpdate(newerDoc, fromNewerBin);
|
||||
const olderDoc = new Doc();
|
||||
applyUpdate(olderDoc, toOlderBin);
|
||||
|
||||
const newerState = encodeStateVector(newerDoc);
|
||||
const olderState = encodeStateVector(olderDoc);
|
||||
|
||||
const diff = encodeStateAsUpdate(newerDoc, olderState);
|
||||
const undoManager = new UndoManager(Array.from(olderDoc.share.values()));
|
||||
|
||||
applyUpdate(olderDoc, diff);
|
||||
undoManager.undo();
|
||||
|
||||
return encodeStateAsUpdate(olderDoc, newerState);
|
||||
return new Uint8Array(
|
||||
serverNative.revertDocUpdateV1(
|
||||
Buffer.from(fromNewerBin),
|
||||
Buffer.from(toOlderBin)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function fail(message: string): never {
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@affine-tools/cli": "workspace:*",
|
||||
"yjs": "^13.6.27"
|
||||
"@affine/server-native": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
|
||||
@@ -4,5 +4,8 @@
|
||||
"outDir": "dist"
|
||||
},
|
||||
"files": ["index.ts"],
|
||||
"references": [{ "path": "../cli" }]
|
||||
"references": [
|
||||
{ "path": "../cli" },
|
||||
{ "path": "../../packages/backend/native" }
|
||||
]
|
||||
}
|
||||
@@ -1448,7 +1448,7 @@ export const PackageList = [
|
||||
{
|
||||
location: 'tools/revert-update',
|
||||
name: '@affine/revert-update',
|
||||
workspaceDependencies: ['tools/cli'],
|
||||
workspaceDependencies: ['tools/cli', 'packages/backend/native'],
|
||||
},
|
||||
{
|
||||
location: 'tools/utils',
|
||||
|
||||
@@ -876,9 +876,9 @@ __metadata:
|
||||
resolution: "@affine/revert-update@workspace:tools/revert-update"
|
||||
dependencies:
|
||||
"@affine-tools/cli": "workspace:*"
|
||||
"@affine/server-native": "workspace:*"
|
||||
"@types/node": "npm:^22.0.0"
|
||||
typescript: "npm:@typescript/typescript6@6.0.2"
|
||||
yjs: "npm:^13.6.27"
|
||||
languageName: unknown
|
||||
linkType: soft
|
||||
|
||||
|
||||
Reference in new issue
Block a user