perf(store): Limit share destination and collection reads

This commit is contained in:
DarkSky committed 2026-12-03 12:42:12 +09:00
1 parent 973588a31d
commit 0a56c8e396
3 files changed
+157 -29

No files matched your search

@@ -294,6 +294,101 @@ const DUPLICATE_COLLECTION_UPDATE: &[u8] = &[
97, 119, 4, 107, 101, 101, 112, 0,
];
#[test]
fn same_name_rename_merges_duplicate_collection_members() -> StoreResult<()> {
for (_, initial) in collection_before_and_after_migration(ARRAY_ALLOW_LIST, &[]) {
let mut doc = fork(10, &initial);
let rename = NavigationEdit::RenameCollection {
id: "c".into(),
name: "Original".into(),
};
assert!(doc.edit_workspace_navigation(&rename, 42)?.is_none());
doc.apply_remote_update(DUPLICATE_COLLECTION_UPDATE)?;
let projected = doc
.navigation_collections()?
.unwrap()
.into_iter()
.find(|row| row.id == "c")
.unwrap();
assert_eq!(
doc.collection_allow_list("c")?,
Some(projected.allow_list.clone())
);
assert_eq!(doc.collection_allow_list("missing")?, None);
assert_eq!(projected.allow_list, ["old", "other"]);
assert!(doc.edit_workspace_navigation(&rename, 42)?.is_some());
let collections = TypeTarget::Path(TypePath::root("setting").key("collections"));
assert_eq!(doc.root.read_array(&collections).unwrap().len(), 1);
assert_eq!(doc.navigation_collections()?, Some(vec![projected]));
assert!(doc.edit_workspace_navigation(&rename, 43)?.is_none());
}
Ok(())
}
#[test]
fn share_destinations_validates_targets_and_appends_only_new_tags() -> StoreResult<()> {
for initial_tags in [
SessionValue::Array(vec![
SessionValue::Any(Any::String("existing".into())),
SessionValue::Any(Any::String("existing".into())),
]),
SessionValue::Any(Any::True),
] {
let mut doc = fork(10, ARRAY_ALLOW_LIST);
doc.create_page(PageIdSource::Explicit("page-one"), "First", 1)?;
doc.define_tag("existing", "Existing", "", 1)?;
doc.define_tag("new", "New", "", 1)?;
let target = doc.find_page_map_target("page-one")?.unwrap();
doc.with_tx(|root| {
root.map_set(&target, "tags".into(), initial_tags)
.map(drop)
.map_err(y_error)
})?;
let tags_before = doc.root.get_map_value(&target, "tags").unwrap();
let before = doc.encode_update_v1()?;
assert!(matches!(
doc.apply_share_destinations("missing", &[], Some("c"), true),
Err(StoreError::DocNotFound(id)) if id == "missing"
));
assert!(matches!(
doc.apply_share_destinations("page-one", &["missing".into()], Some("c"), true),
Err(StoreError::InvalidProtocol(_))
));
assert_eq!(doc.encode_update_v1()?, before);
assert!(
doc.apply_share_destinations("page-one", &[" ".into()], Some("c"), true)?
.is_some()
);
assert_eq!(
doc.root.get_map_value(&target, "tags").unwrap(),
tags_before
);
assert_eq!(
doc.collection_allow_list("c")?,
Some(vec!["old".into(), "page-one".into()])
);
let requested = ["existing".into(), " new ".into(), "new".into()];
assert!(
doc.apply_share_destinations("page-one", &requested, Some("c"), true)?
.is_some()
);
assert_eq!(doc.get_page("page-one")?.unwrap().tags, ["existing", "new"]);
if let Some(SessionReadValue::Array(id)) = tags_before {
assert_eq!(
doc.root.get_map_value(&target, "tags").unwrap(),
Some(SessionReadValue::Array(id))
);
}
assert!(
doc.apply_share_destinations("page-one", &requested, Some("c"), true)?
.is_none()
);
}
Ok(())
}
#[test]
fn delayed_duplicate_keeps_concurrent_collection_rename_and_share() {
let mut seed = fork(1, ARRAY_ALLOW_LIST);
@@ -1,6 +1,7 @@
//! `0.27.5` `ImportClipperService` destination metadata support (`meta.properties.tags.options`,
//! `meta.pages[doc].tags`, and `setting.collections[id].allowList`) for [`WorkspaceRootDoc`].
use std::cell::Cell;
use std::collections::{BTreeMap, BTreeSet};
use y_octo::{Any, DocSession, SessionReadValue, SessionValue, TypePath, TypeTarget};
@@ -55,6 +56,10 @@ pub enum NavigationEdit {
const TAGS: &[&str] = &["properties", "tags", "options"];
const COLLECTIONS: &[&str] = &["collections"];
thread_local! {
static NAVIGATION_COLLECTIONS_CALLS: Cell<usize> = const { Cell::new(0) };
}
impl WorkspaceRootDoc {
/// Convert legacy navigation lists to shared arrays and return their V1 update.
///
@@ -113,6 +118,7 @@ impl WorkspaceRootDoc {
/// Read collection definitions without writing back to the root.
pub fn navigation_collections(&self) -> StoreResult<Option<Vec<WorkspaceCollection>>> {
NAVIGATION_COLLECTIONS_CALLS.with(|calls| calls.set(calls.get().wrapping_add(1)));
let root = &self.root;
let Some(items) = find_list(root, "setting", COLLECTIONS)
.map(|list| array_values(root, list))
@@ -159,6 +165,11 @@ impl WorkspaceRootDoc {
Ok(Some(collections.collect()))
}
#[doc(hidden)]
pub fn navigation_collections_calls() -> usize {
NAVIGATION_COLLECTIONS_CALLS.with(Cell::get)
}
fn read_navigation<T>(
&self,
name: &str,
@@ -194,12 +205,17 @@ impl WorkspaceRootDoc {
/// Return the explicitly included documents of an existing collection.
pub fn collection_allow_list(&self, collection_id: &str) -> StoreResult<Option<Vec<String>>> {
Ok(self
.navigation_collections()?
.into_iter()
.flatten()
.find(|collection| collection.id == collection_id)
.map(|collection| collection.allow_list))
let Some(list) = find_list(&self.root, "setting", COLLECTIONS) else {
return Ok(None);
};
let Some(items) = array_values(&self.root, list)? else {
return Ok(None);
};
let matches = matching_items(&self.root, &items, collection_id);
Ok(
merge_collection(&self.root, matches.into_iter().map(|(_, item)| item))
.map(|record| record.allow_list),
)
}
pub(super) fn edit_workspace_navigation(
@@ -234,16 +250,16 @@ impl WorkspaceRootDoc {
ListEdit::Insert(collection_record(collection))
}
NavigationEdit::RenameCollection { name, .. } => {
if let [(_, item)] = matches.as_slice()
&& field_string(&self.root, item, "name").as_deref() == Some(name)
{
return Ok(None);
}
let Some(record) =
merge_collection(&self.root, matches.iter().map(|(_, item)| *item))
else {
return Ok(None);
};
if matches.len() == 1
&& field_string(&self.root, record.winner, "name").as_deref() == Some(name)
{
return Ok(None);
}
let next_date =
now_ms.max(record.update_date.map_or(1, |date| date.saturating_add(1)));
ListEdit::Replace(record.into_value(&self.root, Some((name, next_date)))?)
@@ -302,7 +318,11 @@ impl WorkspaceRootDoc {
return Ok(None);
}
let defined_tags = self.defined_tag_ids()?;
let defined_tags = if dedup_tags.is_empty() {
BTreeSet::new()
} else {
self.defined_tag_ids()?
};
if require_destinations_exist {
for tag_id in &dedup_tags {
if !defined_tags.contains(tag_id) {
@@ -340,25 +360,32 @@ impl WorkspaceRootDoc {
}
}
let Some(page_target) = self.find_page_map_target(page_id)? else {
let Some(page_target) = self
.find_page_map_target(page_id)?
.filter(|_| !page_id.is_empty())
else {
return Err(StoreError::DocNotFound(page_id.to_string()));
};
let page_meta = self
.get_page(page_id)?
.ok_or_else(|| StoreError::DocNotFound(page_id.to_string()))?;
let existing_page_tags: BTreeSet<String> = page_meta.tags.into_iter().collect();
let tags_to_append: Vec<String> = dedup_tags
.into_iter()
.filter(|id| !existing_page_tags.contains(id) && defined_tags.contains(id))
.collect();
let existing_tags_arr = match self
.root
.get_map_value(&page_target, "tags")
.map_err(|e| StoreError::YOcto(e.to_string()))?
{
Some(SessionReadValue::Array(arr_id)) => Some(TypeTarget::Identity(arr_id)),
_ => None,
let (tags_to_append, existing_tags_arr) = if dedup_tags.is_empty() {
(Vec::new(), None)
} else {
let tags = self
.root
.get_map_value(&page_target, "tags")
.map_err(y_error)?;
let (existing_tags, target) = match tags {
Some(SessionReadValue::Array(id)) => {
let target = TypeTarget::Identity(id.clone());
let tags = self.read_page_tags(SessionReadValue::Array(id))?;
(tags.into_iter().collect::<BTreeSet<_>>(), Some(target))
}
_ => (BTreeSet::new(), None),
};
let added = dedup_tags
.into_iter()
.filter(|id| !existing_tags.contains(id) && defined_tags.contains(id))
.collect::<Vec<_>>();
(added, target)
};
if tags_to_append.is_empty() && col_mutation.is_none() {
@@ -721,7 +721,13 @@ pub(super) mod tests {
let members = (members.as_ptr(), members.len());
let revision = store.derived.meta_rev;
let calls_before = WorkspaceRootDoc::navigation_collections_calls();
assert!(!store.rename_collection("empty", "Empty"));
assert_eq!(
WorkspaceRootDoc::navigation_collections_calls().wrapping_sub(calls_before),
0,
"connected={connected}"
);
let layout = store.collections.as_slice();
assert_eq!((layout.as_ptr(), layout.len()), collections);