fix(backend): upgrade to y-octo 0.4.3 and close server parity and read-gate gaps

- Bump packages/backend to y-octo 0.4.3 (large_refs) and y-octo-core 0.2.0, delegating bounded full and partial Update V1 decoding directly to y_octo::ReadDoc::from_update_v1[_with_limits] in server_domain::yjs_read with shared merge_update_parts[_bounded] helpers and injectable decode semaphore admission.

- Unify workspace lifecycle root-doc migration limits (256 MiB / 16M structs) and shared SQL byte precheck + bounded decode outcomes in server_domain::doc_meta across server-sync and server-worker (including write-tx recheck), keeping ResourceLimit failures non-terminal without writing completed checkpoints.

- Enforce non-blocking decode permit admission with immediate transaction rollback on server-blob readable manifests while keeping warm cache hits permit-free, separate MCP system-doc write cap (64 MiB) from the 16 MiB public root-doc cap, and fail MCP recovery on corrupt decode instead of overwriting workspace_pages metadata.

- Unify 16 MiB root-doc bounds across doc_sharing public and alias-resolution paths, remove test-only counters from DocSharingService in favor of tracing debug events, backfill doc-compactor metadata monotonically, align server-search generation lock key, and update AGENTS.md.
This commit is contained in:
DarkSky committed 2026-11-30 02:39:55 +09:00
1 parent c39a80d0d9
commit cf67d1974e
27 files changed
+4898 -1028

No files matched your search

+11 -2
View File
@@ -35,7 +35,7 @@ Never edit an existing SQL migration file. Add a new versioned file instead.
1. Serialize blob writes and deletes with per-object advisory locks outside the pooled connection.
2. Keep local and S3 object key layouts identical to `v0.27.5`.
3. Keep `v0.27.5` workspace storage reconciliation active during mixed rollout until `affine-server` owns orphan object sweeps.
3. Run only one maintenance worker stack against a database at a time (`server-blob` includes `reconcile_storage_orphans`). Before you cut over or run mixed `front` or `graphql` instances, stop Node `SERVER_FLAVOR=worker` and start `affine-server --role worker` first.
4. `provider: "assetpack"` enables `config.precomp2 = true` by default (writing `PCF2 v2` recipes while decoding `v0.27.5` `PCF2 v1`, `PCF2 v2`, and raw FastCDC chunks). Set `config.precomp2 = false` during mixed rollout with `v0.27.5` or while keeping a rollback window to `v0.27.5` so newly written objects remain readable by `v0.27.5`.
5. `AssetpackBlobStorage` bounds total decoded transform output per read to `512 MiB` (`DECODE_MAX_TOTAL_OUTPUT_BYTES`, 4x the `128 MiB` `FileTransformConfig::fast()` write transform cap). Legacy `v0.27.5` `PCF2 v1` PNG objects whose uncompressed pixel stream exceeds `512 MiB` (for example RGB images above roughly `13,000 x 13,000` or RGBA images above roughly `11,500 x 11,500`) remain intact on disk, and reading them returns a `decode output exceeds budget` error instead of allocating unbounded memory.
@@ -61,10 +61,19 @@ Trigger and fence rules:
2. Multi-workspace permission updates lock workspace keys in `LEAST` then `GREATEST` order to prevent deadlocks.
3. The two-step `fenceXid` discovery fence requires writers to use `READ COMMITTED` isolation.
4. In steady state, ordinary document snapshot writes skip redundant updates to `search_projection.workspace_states`.
5. Generation creation and activation take only `search-projection-lifecycle`.
5. Generation creation and activation take `search-projection-generation` to serialize with `v0.27.5`.
Orphan GC takes only `search-projection-ws:<workspace_id>` with a `source_version <= H` bound.
If all `server-search` workers stop, triggers revert to the global shared lock after 90 seconds.
Set `idle_in_transaction_session_timeout` to `>= 60s` on the legacy database role.
`v0.27.5` lazy compaction can wait up to 60 seconds for a Redis lock.
This timeout still bounds idle transactions that stall `pg_snapshot_xmin`.
## 7. Mixed-Stack Runtime Constraints
These rules apply when `affine-server` runs beside the current `beta` or `stable` release from `canary`.
1. Socket.IO clients must use the `websocket` transport during mixed runs and cutover. The `affine-server` process keeps Engine.IO HTTP `polling` sessions in local memory. Cross-instance `polling` requests without stickiness return HTTP `400`.
2. Run only one maintenance worker stack at a time. Before you route write traffic to `affine-server` `front` or `graphql` instances, stop Node `SERVER_FLAVOR=worker` and start `affine-server --role worker` first. `affine-server --role worker` works with `canary` Node `front` and `graphql` instances. This prevents delayed Node `DocJobRunner` events from overwriting newer metadata from `affine-server` writes.
3. Do not run `AFFINE_INDEXER_PROVIDER=embedded` on both Node and `affine-server` against the same PostgreSQL database. Use shared external `elasticsearch` or `manticoresearch`, or enable search on one stack only.
4. During mixed runs, the Prometheus metric `sync_active_users_minutely` reports active connections on the local server stack only. Counts converge after full traffic cutover.
+3 -2
View File
@@ -46,6 +46,7 @@ It excludes `native/` and `server/` and does not join the root `Cargo.toml` work
`CalendarService` manages Google Calendar OAuth (`SessionRedis` `CALENDAR_OAUTH_STATE:<UUID>`), CalDAV discovery/sync over `safe_fetch` + `xmlparser`, 12B IV + 12B tag AES-256-GCM credential encryption, and pool-safe polling without holding PostgreSQL connections across external HTTP requests.
`McpCredentialService` manages `aff_mcp_v1.<id>.<secret>` workspace credentials with family-level `FOR UPDATE` rotation locking (24h grace), family-wide revocation, and `y-octo` document read/write operations under `workspace-doc-update` advisory locks.
`acl` defines workspace and document permissions and classifies reserved documents.
`doc_sharing` bounds workspace root doc reads at `16 MiB` (`MAX_PUBLIC_ROOT_DOC_BYTES`). Legacy workspaces that have not completed `workspace_doc_lifecycle` and whose root doc snapshot plus updates exceed `16 MiB` fail closed on alias-resolution routes until lifecycle migration completes; direct public root-doc HTTP routes (`GET /public-docs/:workspaceId` and `GET /public-docs/:docId/root-doc`) permanently cap root-doc binaries at `16 MiB` regardless of lifecycle state (Socket.IO sync is unaffected).
`server-domain` has no `legacy_compat`, `phase_a_compat`, `axum`, or `async-graphql` dependencies.
- `server-mail` (library `server_mail`): 30 compiled `v0.27.5` HTML email templates, `SmtpMailer` (`lettre` + `rustls`), and `process_ready_mail_deliveries`.
@@ -65,8 +66,8 @@ It excludes `native/` and `server/` and does not join the root `Cargo.toml` work
It isolates `legacy_compat::errors` and bridges Redis `affine:eventbus:v1` and invalidation events.
- `server-search` (library `server_search`): pure-Rust search runtime (`embedded`, `elasticsearch`, and `manticoresearch`) with no `napi` or `affine_doc_loader` dependency.
It extracts document titles, blocks, and canvas elements directly with `y-octo`.
It renews the 90s `search_projection_lockless_v2` lease every 15s and serializes generations on `search-projection-lifecycle` with an `xid8` fence.
It extracts document titles, blocks, and canvas elements directly with `y-octo` under a `32 MiB` document binary cap.
It renews the 90s `search_projection_lockless_v2` lease every 15s without global locks. Generation creation and activation serialize on `search-projection-generation` with `v0.27.5` under an `xid8` fence.
It fences orphan GC per workspace on `search-projection-ws:<workspace_id>`.
- `server-http` (library `server_http`): `axum 0.8` and `async-graphql 7` transport layer with `/healthz`, `/readyz`, `/info`, and `/graphql` (including workspace `search`, `aggregate`, `searchDocs`, `workspaceRolePermissions`, `DocType.{analytics, lastAccessedMembers}`, multipart blob upload mutations `createBlobUpload`, `completeBlobUpload`, `abortBlobUpload`, `WorkspaceType.blobUploadPartUrl`, admin console user, workspace, dashboard, shared-link, mail-delivery, and app-config metadata/validation queries and mutations, auth security challenges, signing key rotation, `UserType.token`, and `Query.error`).
+4 -4
View File
@@ -5796,9 +5796,9 @@ checksum = "66fee0b777b0f5ac1c69bb06d361268faafa61cd4682ae064a171c16c433e9e4"
[[package]]
name = "y-octo"
version = "0.4.2"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ca83593de45d6f6bd0118d8199ccb2a13ec9a3b572b962c2b9a6149c443443d"
checksum = "39f545545da7703535ab0fdce22d6006c91a1e4b159ba863f2f5d3edb90d4d98"
dependencies = [
"ahash",
"arbitrary",
@@ -5820,9 +5820,9 @@ dependencies = [
[[package]]
name = "y-octo-core"
version = "0.1.1"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca7f2eed556822e81c35f76c8a27855daca946bf1818707ddcd5b9d4434dc6f"
checksum = "3f33df5bbde25f7e99f2fee94a7e94b5207f3837485a8562655368d24437d1da"
[[package]]
name = "yoke"
+2 -2
View File
@@ -78,8 +78,8 @@ url = "2.5"
uuid = { version = "1", features = ["v4", "serde"] }
v_htmlescape = "0.15"
xmlparser = "0.13"
y-octo = { version = "0.4.2", features = ["large_refs"] }
y-octo-core = "0.1.1"
y-octo = { version = "0.4.3", features = ["large_refs"] }
y-octo-core = "0.2.0"
zeroize = "1"
zstd = "0.14"
+7
View File
@@ -415,6 +415,7 @@ pub struct BlobService {
quota: Arc<dyn QuotaGate>,
pub(crate) invalidation: Option<Arc<dyn server_domain::events::InvalidationPublisher>>,
pub(crate) lock_permits: Arc<Semaphore>,
pub(crate) decode_semaphore: Arc<Semaphore>,
ref_cache: Arc<std::sync::Mutex<refs::BlobRefCache>>,
}
@@ -431,10 +432,16 @@ impl BlobService {
quota,
invalidation: None,
lock_permits: Arc::new(Semaphore::new(DEFAULT_STORAGE_LOCK_CONCURRENCY)),
decode_semaphore: Arc::clone(server_domain::yjs_read::doc_decode_semaphore()),
ref_cache: Arc::new(std::sync::Mutex::new(refs::BlobRefCache::new())),
}
}
pub fn with_decode_semaphore(mut self, semaphore: Arc<Semaphore>) -> Self {
self.decode_semaphore = semaphore;
self
}
pub fn with_invalidation(mut self, invalidation: Arc<dyn server_domain::events::InvalidationPublisher>) -> Self {
self.invalidation = Some(invalidation);
self
+253 -130
View File
@@ -4,6 +4,7 @@
use std::collections::{BTreeSet, HashSet, VecDeque};
use std::num::NonZeroUsize;
use std::sync::Arc;
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
@@ -12,9 +13,12 @@ use lru::LruCache;
use serde::{Deserialize, Serialize};
use server_db::WorkloadTier;
use server_domain::acl::{authorize_reserved_doc, load_workspace_docs_access_in};
use server_domain::yjs_read::{
load_yjs_doc_with_limits, merge_update_parts, run_with_decode_semaphore, try_run_with_decode_semaphore,
};
use server_types::DomainError;
use sqlx::{Postgres, Transaction};
use y_octo::{ReadDoc, ReadMap, ReadValue};
use y_octo::{ReadMap, ReadValue};
use crate::{BlobRecord, BlobService};
@@ -131,30 +135,35 @@ enum LoadedRefSource {
pub fn live_blob_keys_from_updates(
updates: Vec<Vec<u8>>,
workspace_root: bool,
) -> Result<BTreeSet<String>, DomainError> {
live_blob_keys_from_updates_with_limits(updates, workspace_root, y_octo::ReadLimits::default())
}
fn live_blob_keys_from_updates_with_limits(
updates: Vec<Vec<u8>>,
workspace_root: bool,
limits: y_octo::ReadLimits,
) -> Result<BTreeSet<String>, DomainError> {
if updates.is_empty() {
return Ok(BTreeSet::new());
}
let merged = if updates.len() == 1 {
updates.into_iter().next().unwrap_or_default()
} else {
y_octo::merge_updates_v1(&updates)
.and_then(|u| u.encode_v1())
.map_err(|err| DomainError::Internal(format!("failed to merge document updates: {err}")))?
};
let merged = merge_update_parts(updates)
.map_err(|err| DomainError::Internal(format!("failed to merge document updates: {err}")))?;
if merged.len() > MAX_SOURCE_BINARY_BYTES {
return Err(DomainError::Internal("blob_ref_source_too_large".into()));
}
let doc = ReadDoc::from_full_update_v1(merged)
let doc = load_yjs_doc_with_limits(Arc::<[u8]>::from(merged), limits)
.map_err(|err| DomainError::Internal(format!("invalid document binary: {err}")))?;
let mut keys = BTreeSet::new();
if workspace_root
&& let Some(meta) = doc.map("meta")
&& let Some(avatar) = string_value(meta, "avatar")
&& !avatar.is_empty()
{
insert_key(&mut keys, avatar)?;
if workspace_root {
if let Some(meta) = doc.map("meta")
&& let Some(avatar) = string_value(meta, "avatar")
&& !avatar.is_empty()
{
insert_key(&mut keys, avatar)?;
}
return Ok(keys);
}
let Some(blocks) = doc.map("blocks") else {
@@ -183,7 +192,7 @@ pub fn live_blob_keys_from_updates(
let mut queue = VecDeque::from([root.clone()]);
let mut discovered = HashSet::from([root]);
while let Some(block_id) = queue.pop_front() {
let Some(block) = blocks.get(&block_id).and_then(|value| value.as_map()) else {
let Some(block) = blocks.get(&block_id).and_then(ReadValue::as_map) else {
continue;
};
if matches!(
@@ -194,7 +203,7 @@ pub fn live_blob_keys_from_updates(
{
insert_key(&mut keys, key)?;
}
if let Some(children) = block.get("sys:children").and_then(|value| value.as_array()) {
if let Some(children) = block.get("sys:children").and_then(ReadValue::as_array) {
if children.len() > MAX_CHILDREN_PER_BLOCK {
return Err(DomainError::Internal("blob_ref_tree_fanout_too_large".into()));
}
@@ -214,6 +223,14 @@ pub fn live_blob_keys_from_updates(
Ok(keys)
}
fn string_value(map: ReadMap<'_>, key: &str) -> Option<String> {
match map.get(key)? {
ReadValue::Any(value) => value.as_str().map(str::to_owned),
ReadValue::Text(value) => Some(value.to_string()),
_ => None,
}
}
fn insert_key(keys: &mut BTreeSet<String>, key: String) -> Result<(), DomainError> {
if key.len() > MAX_BLOB_KEY_BYTES {
return Err(DomainError::Internal("blob_ref_key_too_large".into()));
@@ -225,14 +242,6 @@ fn insert_key(keys: &mut BTreeSet<String>, key: String) -> Result<(), DomainErro
Ok(())
}
fn string_value(map: ReadMap<'_>, key: &str) -> Option<String> {
match map.get(key)? {
ReadValue::Any(value) => value.as_str().map(str::to_owned),
ReadValue::Text(value) => Some(value.to_string()),
_ => None,
}
}
fn encode_cursor(doc_id: &str, key: &str) -> String {
let payload = serde_json::to_vec(&ReadableManifestCursor {
doc_id: doc_id.to_owned(),
@@ -261,7 +270,7 @@ impl BlobService {
.await?;
match loaded {
None => Ok(None),
Some(src) => Ok(Some(self.extract_and_cache_source(src).await?)),
Some(src) => Ok(Some(self.extract_and_cache_source(src, true).await?)),
}
}
@@ -427,7 +436,11 @@ impl BlobService {
}))
}
async fn extract_and_cache_source(&self, source: LoadedRefSource) -> Result<BTreeSet<String>, DomainError> {
async fn extract_and_cache_source(
&self,
source: LoadedRefSource,
non_blocking_admission: bool,
) -> Result<BTreeSet<String>, DomainError> {
match source {
LoadedRefSource::Cached(keys) => Ok(keys),
LoadedRefSource::Buffers {
@@ -435,9 +448,18 @@ impl BlobService {
buffers,
is_root,
} => {
let keys = tokio::task::spawn_blocking(move || live_blob_keys_from_updates(buffers, is_root))
.await
.map_err(|err| DomainError::Internal(format!("blob ref extraction task failed: {err}")))??;
let keys = if non_blocking_admission {
try_run_with_decode_semaphore(&self.decode_semaphore, move || {
live_blob_keys_from_updates(buffers, is_root)
})
.await?
.ok_or_else(|| DomainError::Unavailable("Document decode permits are busy; please retry.".to_owned()))?
} else {
run_with_decode_semaphore(&self.decode_semaphore, move || {
live_blob_keys_from_updates(buffers, is_root)
})
.await?
};
if let Ok(mut cache) = self.ref_cache.lock() {
cache.put(cache_key, keys.clone());
}
@@ -547,7 +569,7 @@ impl BlobService {
let _ = tx.rollback().await;
match loaded {
None => Ok(None),
Some(src) => Ok(Some(self.extract_and_cache_source(src).await?)),
Some(src) => Ok(Some(self.extract_and_cache_source(src, false).await?)),
}
}
@@ -634,117 +656,122 @@ impl BlobService {
.begin_tiered(WorkloadTier::InteractiveRead)
.await
.map_err(|err| DomainError::Internal(err.to_string()))?;
sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
.execute(&mut **tx.tx_mut())
.await
.map_err(|err| DomainError::Internal(err.to_string()))?;
let now: DateTime<Utc> = sqlx::query_scalar("SELECT clock_timestamp()")
.fetch_one(&mut **tx.tx_mut())
.await
.map_err(|err| DomainError::Internal(err.to_string()))?;
let result: Result<Vec<SourceBlobManifestEntry>, DomainError> = async {
sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
.execute(&mut **tx.tx_mut())
.await
.map_err(|err| DomainError::Internal(err.to_string()))?;
let ws_acl = load_workspace_docs_access_in(
tx.tx_mut(),
self.quota.as_ref(),
workspace_id,
Some(actor_user_id),
&[],
now,
)
.await?;
if !ws_acl.workspace_permissions.sync {
let _ = tx.rollback().await;
return Err(DomainError::Forbidden("Workspace sync access denied".into()));
}
let now: DateTime<Utc> = sqlx::query_scalar("SELECT clock_timestamp()")
.fetch_one(&mut **tx.tx_mut())
.await
.map_err(|err| DomainError::Internal(err.to_string()))?;
let candidate_docs: Vec<String> = sqlx::query_scalar(
"SELECT d.guid
FROM (
SELECT guid FROM snapshots WHERE workspace_id = $1
UNION
SELECT guid FROM updates WHERE workspace_id = $1
) d
WHERE ($2::text IS NULL OR d.guid >= $2)
AND NOT EXISTS (
SELECT 1 FROM workspace_pages wp
WHERE wp.workspace_id = $1
AND wp.page_id = d.guid
AND wp.lifecycle_state = 'deleted'
)
ORDER BY d.guid ASC",
)
.bind(workspace_id)
.bind(cursor_doc_id)
.fetch_all(&mut **tx.tx_mut())
.await
.map_err(|err| DomainError::Internal(err.to_string()))?;
let mut entries = Vec::with_capacity(page_limit + 1);
for chunk in candidate_docs.chunks(200) {
let filtered_reserved: Vec<String> = chunk
.iter()
.filter(|doc_id| authorize_reserved_doc(workspace_id, doc_id, Some(actor_user_id)))
.cloned()
.collect();
if filtered_reserved.is_empty() {
continue;
}
let chunk_acl = load_workspace_docs_access_in(
let ws_acl = load_workspace_docs_access_in(
tx.tx_mut(),
self.quota.as_ref(),
workspace_id,
Some(actor_user_id),
&filtered_reserved,
&[],
now,
)
.await?;
if !ws_acl.workspace_permissions.sync {
return Err(DomainError::Forbidden("Workspace sync access denied".into()));
}
for doc_id in filtered_reserved {
let Some(entry) = chunk_acl.docs.get(&doc_id) else {
continue;
};
let is_root = entry.storage_doc_id == workspace_id;
let can_read = if is_root {
chunk_acl.workspace_permissions.read
} else {
!entry.deleted && entry.permissions.doc_read
};
if !can_read {
let candidate_docs: Vec<String> = sqlx::query_scalar(
"SELECT d.guid
FROM (
SELECT guid FROM snapshots WHERE workspace_id = $1
UNION
SELECT guid FROM updates WHERE workspace_id = $1
) d
WHERE ($2::text IS NULL OR d.guid >= $2)
AND NOT EXISTS (
SELECT 1 FROM workspace_pages wp
WHERE wp.workspace_id = $1
AND wp.page_id = d.guid
AND wp.lifecycle_state = 'deleted'
)
ORDER BY d.guid ASC",
)
.bind(workspace_id)
.bind(cursor_doc_id)
.fetch_all(&mut **tx.tx_mut())
.await
.map_err(|err| DomainError::Internal(err.to_string()))?;
let mut entries = Vec::with_capacity(page_limit + 1);
for chunk in candidate_docs.chunks(200) {
let filtered_reserved: Vec<String> = chunk
.iter()
.filter(|doc_id| authorize_reserved_doc(workspace_id, doc_id, Some(actor_user_id)))
.cloned()
.collect();
if filtered_reserved.is_empty() {
continue;
}
let Some(keys) = self
.load_current_doc_keys_in_tx(tx.tx_mut(), workspace_id, &entry.storage_doc_id)
.await?
else {
continue;
};
if keys.is_empty() {
continue;
}
let chunk_acl = load_workspace_docs_access_in(
tx.tx_mut(),
self.quota.as_ref(),
workspace_id,
Some(actor_user_id),
&filtered_reserved,
now,
)
.await?;
let key_vec: Vec<String> = keys.into_iter().collect();
let after_key = match &decoded_cursor {
Some(cur) if doc_id == cur.doc_id => Some(cur.key.as_str()),
_ => None,
};
let remaining = (page_limit + 1).saturating_sub(entries.len()) as i64;
let blobs =
list_live_blobs_by_keys_in_tx(tx.tx_mut(), workspace_id, &key_vec, after_key, Some(remaining)).await?;
for b in blobs {
entries.push(SourceBlobManifestEntry {
key: b.key,
size: b.size,
mime: b.mime,
created_at: b.created_at,
source_type: "currentDoc".to_owned(),
workspace_id: workspace_id.to_owned(),
doc_id: doc_id.clone(),
timestamp_ms: None,
});
for doc_id in filtered_reserved {
let Some(entry) = chunk_acl.docs.get(&doc_id) else {
continue;
};
let is_root = entry.storage_doc_id == workspace_id;
let can_read = if is_root {
chunk_acl.workspace_permissions.read
} else {
!entry.deleted && entry.permissions.doc_read
};
if !can_read {
continue;
}
let Some(keys) = self
.load_current_doc_keys_in_tx(tx.tx_mut(), workspace_id, &entry.storage_doc_id)
.await?
else {
continue;
};
if keys.is_empty() {
continue;
}
let key_vec: Vec<String> = keys.into_iter().collect();
let after_key = match &decoded_cursor {
Some(cur) if doc_id == cur.doc_id => Some(cur.key.as_str()),
_ => None,
};
let remaining = (page_limit + 1).saturating_sub(entries.len()) as i64;
let blobs =
list_live_blobs_by_keys_in_tx(tx.tx_mut(), workspace_id, &key_vec, after_key, Some(remaining)).await?;
for b in blobs {
entries.push(SourceBlobManifestEntry {
key: b.key,
size: b.size,
mime: b.mime,
created_at: b.created_at,
source_type: "currentDoc".to_owned(),
workspace_id: workspace_id.to_owned(),
doc_id: doc_id.clone(),
timestamp_ms: None,
});
if entries.len() > page_limit {
break;
}
}
if entries.len() > page_limit {
break;
}
@@ -753,12 +780,13 @@ impl BlobService {
break;
}
}
if entries.len() > page_limit {
break;
}
Ok(entries)
}
.await;
let _ = tx.rollback().await;
let mut entries = result?;
let next_cursor = if entries.len() > page_limit {
entries.truncate(page_limit);
@@ -966,4 +994,99 @@ mod tests {
.expect("live_blob_keys_from_updates must succeed");
assert_eq!(keys, BTreeSet::from(["blob-att-1".to_owned(), "blob-img-1".to_owned()]));
}
#[test]
fn live_blob_keys_enforces_resource_limit_without_unbounded_fallback() {
let doc = y_octo::Doc::with_client(202);
let mut meta = doc.get_or_create_map("meta").unwrap();
meta
.insert("avatar".to_owned(), y_octo::Any::String("avatar-1".into()))
.unwrap();
meta
.insert("name".to_owned(), y_octo::Any::String("workspace-1".into()))
.unwrap();
let bin = doc.encode_update_v1().unwrap();
let tiny_limits = y_octo::ReadLimits {
max_structs: 1,
..y_octo::ReadLimits::default()
};
let err = live_blob_keys_from_updates_with_limits(vec![bin], true, tiny_limits)
.expect_err("exceeding ReadLimits must return error without unbounded fallback");
assert!(
matches!(err, DomainError::Internal(ref msg) if msg.contains("invalid document binary")),
"expected resource limit error, got {err:?}"
);
}
#[test]
fn live_blob_keys_recover_incomplete_snapshot_for_workspace_root_and_page_doc() {
// 1. Workspace root doc with client clock gap (IncompleteSnapshot).
let root_c1 = y_octo::DocOptions::new().with_client_id(501).build();
let mut meta = root_c1.get_or_create_map("meta").unwrap();
meta
.insert("avatar".to_owned(), y_octo::Any::String("avatar-gap-key".into()))
.unwrap();
let mut root_c2 = y_octo::DocOptions::new().with_client_id(502).build();
let mut other = root_c2.get_or_create_map("other").unwrap();
other.insert("a".to_owned(), y_octo::Any::String("1".into())).unwrap();
let sv_root = root_c2.get_state_vector();
other.insert("b".to_owned(), y_octo::Any::String("2".into())).unwrap();
root_c2
.apply_update_from_binary_v1(root_c1.encode_update_v1().unwrap())
.unwrap();
let root_delta = root_c2.encode_state_as_update_v1(&sv_root).unwrap();
assert!(matches!(
y_octo::ReadDoc::from_full_update_v1(root_delta.clone()),
Err(y_octo::ReadError::IncompleteSnapshot(_))
));
let root_keys = live_blob_keys_from_updates(vec![root_delta], true)
.expect("incomplete snapshot workspace root must extract avatar key");
assert_eq!(root_keys, BTreeSet::from(["avatar-gap-key".to_owned()]));
// 2. Page doc with client clock gap (IncompleteSnapshot).
let page_c1 = y_octo::DocOptions::new().with_client_id(503).build();
let mut blocks = page_c1.get_or_create_map("blocks").unwrap();
let mut page = page_c1.create_map().unwrap();
page
.insert("sys:id".to_owned(), y_octo::Any::String("p-gap".into()))
.unwrap();
page
.insert("sys:flavour".to_owned(), y_octo::Any::String("affine:page".into()))
.unwrap();
let mut children = page_c1.create_array().unwrap();
children.push(y_octo::Any::String("img-gap".into())).unwrap();
page.insert("sys:children".to_owned(), children).unwrap();
blocks.insert("p-gap".to_owned(), page).unwrap();
let mut img = page_c1.create_map().unwrap();
img
.insert("sys:id".to_owned(), y_octo::Any::String("img-gap".into()))
.unwrap();
img
.insert("sys:flavour".to_owned(), y_octo::Any::String("affine:image".into()))
.unwrap();
img
.insert("prop:sourceId".to_owned(), y_octo::Any::String("blob-gap-img".into()))
.unwrap();
blocks.insert("img-gap".to_owned(), img).unwrap();
let mut page_c2 = y_octo::DocOptions::new().with_client_id(504).build();
let mut scratch = page_c2.get_or_create_map("scratch").unwrap();
scratch.insert("x".to_owned(), y_octo::Any::String("1".into())).unwrap();
let sv_page = page_c2.get_state_vector();
scratch.insert("y".to_owned(), y_octo::Any::String("2".into())).unwrap();
page_c2
.apply_update_from_binary_v1(page_c1.encode_update_v1().unwrap())
.unwrap();
let page_delta = page_c2.encode_state_as_update_v1(&sv_page).unwrap();
assert!(matches!(
y_octo::ReadDoc::from_full_update_v1(page_delta.clone()),
Err(y_octo::ReadError::IncompleteSnapshot(_))
));
let page_keys = live_blob_keys_from_updates(vec![page_delta], false)
.expect("incomplete snapshot page doc must extract image key");
assert_eq!(page_keys, BTreeSet::from(["blob-gap-img".to_owned()]));
}
}
@@ -1037,3 +1037,319 @@ fn reconcile_cleans_only_ownerless_workspaces_older_than_24h_and_their_orphan_ro
);
});
}
#[test]
fn blob_manifests_handle_large_workspace_root_doc() {
let lease = leased_0275_database();
runtime().block_on(async {
let db = ServerDb::connect(DbConfig::new(lease.url())).await.expect("connect db");
sqlx::raw_sql("DROP SCHEMA public CASCADE; CREATE SCHEMA public;")
.execute(db.pool())
.await
.expect("reset schema");
db.ensure_schema_ready().await.expect("ensure schema ready");
let dir = std::env::temp_dir().join(format!("server-blob-manifest-{}", uuid::Uuid::new_v4().simple()));
let _guard = TempDir(dir.clone());
let storage = Arc::new(LocalFsBlobStorage::new(dir.to_str().unwrap(), "blobs").unwrap());
let owner_id = format!("owner-{}", uuid::Uuid::new_v4().simple());
let ws_id = format!("ws-{}", uuid::Uuid::new_v4().simple());
sqlx::query("INSERT INTO users (id, name, email) VALUES ($1, 'Owner', $2)")
.bind(&owner_id)
.bind(format!("{owner_id}@example.test"))
.execute(db.pool())
.await
.unwrap();
sqlx::query("INSERT INTO workspaces (id) VALUES ($1)")
.bind(&ws_id)
.execute(db.pool())
.await
.unwrap();
sqlx::query(
"INSERT INTO workspace_members (id, workspace_id, user_id, role, source, state, created_at, updated_at)
VALUES ($1, $2, $3, 'owner', 'legacy', 'active', now(), now())",
)
.bind(uuid::Uuid::new_v4().to_string())
.bind(&ws_id)
.bind(&owner_id)
.execute(db.pool())
.await
.unwrap();
// Build a synthetic >1.5 MiB workspace root doc with 1,300 meta.pages entries, meta.avatar,
// and a client clock gap so ReadDoc::from_full_update_v1 returns IncompleteSnapshot.
let root_c1 = y_octo::DocOptions::new().with_client_id(301).build();
let mut meta = root_c1.get_or_create_map("meta").unwrap();
meta
.insert("avatar".to_owned(), y_octo::Any::String("avatar-large-root".into()))
.unwrap();
let mut pages = root_c1.create_array().unwrap();
let pad = "p".repeat(1_200);
for idx in 0..1_300 {
let mut entry = root_c1.create_map().unwrap();
entry
.insert("id".to_owned(), y_octo::Any::String(format!("synthetic-page-{idx:04}")))
.unwrap();
entry
.insert("title".to_owned(), y_octo::Any::String(format!("Title {idx:04} {pad}")))
.unwrap();
pages.push(entry).unwrap();
}
meta.insert("pages".to_owned(), pages).unwrap();
let mut root_c2 = y_octo::DocOptions::new().with_client_id(303).build();
let mut scratch = root_c2.get_or_create_map("scratch").unwrap();
scratch
.insert("a".to_owned(), y_octo::Any::String("before".into()))
.unwrap();
let sv_c2 = root_c2.get_state_vector();
scratch
.insert("b".to_owned(), y_octo::Any::String("after".into()))
.unwrap();
root_c2
.apply_update_from_binary_v1(root_c1.encode_update_v1().unwrap())
.unwrap();
let root_bin = root_c2.encode_state_as_update_v1(&sv_c2).unwrap();
assert!(
root_bin.len() > 1_500_000,
"synthetic root doc must exceed 1.5 MiB, got {} bytes",
root_bin.len()
);
assert!(
matches!(
y_octo::ReadDoc::from_full_update_v1(root_bin.clone()),
Err(y_octo::ReadError::IncompleteSnapshot(_))
),
"synthetic large root doc must exercise IncompleteSnapshot client clock gap path"
);
// Build a valid page doc with one image blob reference.
let img_doc = y_octo::Doc::with_client(302);
let mut blocks = img_doc.get_or_create_map("blocks").unwrap();
let mut page = img_doc.create_map().unwrap();
page
.insert("sys:id".to_owned(), y_octo::Any::String("page-root".into()))
.unwrap();
page
.insert("sys:flavour".to_owned(), y_octo::Any::String("affine:page".into()))
.unwrap();
let mut children = img_doc.create_array().unwrap();
children.push(y_octo::Any::String("img-block".into())).unwrap();
page.insert("sys:children".to_owned(), children).unwrap();
blocks.insert("page-root".to_owned(), page).unwrap();
let mut img = img_doc.create_map().unwrap();
img
.insert("sys:id".to_owned(), y_octo::Any::String("img-block".into()))
.unwrap();
img
.insert("sys:flavour".to_owned(), y_octo::Any::String("affine:image".into()))
.unwrap();
img
.insert("prop:sourceId".to_owned(), y_octo::Any::String("blob-valid-img".into()))
.unwrap();
blocks.insert("img-block".to_owned(), img).unwrap();
let img_doc_bin = img_doc.encode_update_v1().unwrap();
for (guid, bin) in [
(ws_id.as_str(), root_bin.as_slice()),
("doc-valid-img", img_doc_bin.as_slice()),
] {
sqlx::query("INSERT INTO snapshots (workspace_id, guid, blob, size, created_at, updated_at) VALUES ($1, $2, $3, $4, now(), now())")
.bind(&ws_id)
.bind(guid)
.bind(bin)
.bind(bin.len() as i64)
.execute(db.pool())
.await
.unwrap();
}
let service = BlobService::new(
db.clone(),
storage,
Arc::new(FixedQuotaGate {
blob_limit: 1 << 20,
storage_quota: 1 << 30,
seat_limit: 10,
}),
);
service
.put_blob(&ws_id, "avatar-large-root", "image/png", b"png-avatar".to_vec())
.await
.unwrap();
service
.put_blob(&ws_id, "blob-valid-img", "image/png", b"png-image".to_vec())
.await
.unwrap();
let root_manifest = service
.get_doc_blob_manifest(&ws_id, "currentDoc", &ws_id, None, Some(&owner_id))
.await
.expect("large workspace root doc manifest must succeed");
assert_eq!(
root_manifest.iter().map(|e| e.key.as_str()).collect::<Vec<_>>(),
vec!["avatar-large-root"]
);
let readable = service
.get_readable_blob_manifest(&ws_id, &owner_id, None, 100)
.await
.expect("readable blob manifest with large workspace root doc must succeed");
let mut keys: Vec<&str> = readable.entries.iter().map(|e| e.key.as_str()).collect();
keys.sort();
assert_eq!(keys, vec!["avatar-large-root", "blob-valid-img"]);
});
}
#[test]
fn readable_blob_manifest_fails_fast_when_decode_permits_busy_and_serves_cache_hits() {
let lease = leased_0275_database();
runtime().block_on(async {
let mut cfg = DbConfig::new(lease.url());
cfg.max_connections = 2;
let db = ServerDb::connect(cfg).await.expect("connect db");
sqlx::raw_sql("DROP SCHEMA public CASCADE; CREATE SCHEMA public;")
.execute(db.pool())
.await
.expect("reset schema");
db.ensure_schema_ready().await.expect("ensure schema ready");
let dir = std::env::temp_dir().join(format!("server-blob-manifest-sem-{}", uuid::Uuid::new_v4().simple()));
let _guard = TempDir(dir.clone());
let storage = Arc::new(LocalFsBlobStorage::new(dir.to_str().unwrap(), "blobs").unwrap());
let owner_id = format!("owner-{}", uuid::Uuid::new_v4().simple());
let ws_id = format!("ws-{}", uuid::Uuid::new_v4().simple());
sqlx::query("INSERT INTO users (id, name, email) VALUES ($1, 'Owner', $2)")
.bind(&owner_id)
.bind(format!("{owner_id}@example.test"))
.execute(db.pool())
.await
.unwrap();
sqlx::query("INSERT INTO workspaces (id) VALUES ($1)")
.bind(&ws_id)
.execute(db.pool())
.await
.unwrap();
sqlx::query(
"INSERT INTO workspace_members (id, workspace_id, user_id, role, source, state, created_at, updated_at)
VALUES ($1, $2, $3, 'owner', 'legacy', 'active', now(), now())",
)
.bind(uuid::Uuid::new_v4().to_string())
.bind(&ws_id)
.bind(&owner_id)
.execute(db.pool())
.await
.unwrap();
let build_img_doc = |client_id: u64, blob_key: &str| {
let doc = y_octo::Doc::with_client(client_id);
let mut blocks = doc.get_or_create_map("blocks").unwrap();
let mut page = doc.create_map().unwrap();
page
.insert("sys:id".to_owned(), y_octo::Any::String("page-root".into()))
.unwrap();
page
.insert("sys:flavour".to_owned(), y_octo::Any::String("affine:page".into()))
.unwrap();
let mut children = doc.create_array().unwrap();
children.push(y_octo::Any::String("img-block".into())).unwrap();
page.insert("sys:children".to_owned(), children).unwrap();
blocks.insert("page-root".to_owned(), page).unwrap();
let mut img = doc.create_map().unwrap();
img
.insert("sys:id".to_owned(), y_octo::Any::String("img-block".into()))
.unwrap();
img
.insert("sys:flavour".to_owned(), y_octo::Any::String("affine:image".into()))
.unwrap();
img
.insert("prop:sourceId".to_owned(), y_octo::Any::String(blob_key.into()))
.unwrap();
blocks.insert("img-block".to_owned(), img).unwrap();
doc.encode_update_v1().unwrap()
};
for (guid, client_id, blob_key) in [("doc-a", 401, "blob-a"), ("doc-b", 402, "blob-b")] {
let bin = build_img_doc(client_id, blob_key);
sqlx::query(
"INSERT INTO snapshots (workspace_id, guid, blob, size, created_at, updated_at)
VALUES ($1, $2, $3, $4, now(), now())",
)
.bind(&ws_id)
.bind(guid)
.bind(&bin)
.bind(bin.len() as i64)
.execute(db.pool())
.await
.unwrap();
}
let sem = Arc::new(tokio::sync::Semaphore::new(2));
let service = BlobService::new(
db.clone(),
storage,
Arc::new(FixedQuotaGate {
blob_limit: 1 << 20,
storage_quota: 1 << 30,
seat_limit: 10,
}),
)
.with_decode_semaphore(Arc::clone(&sem));
service
.put_blob(&ws_id, "blob-a", "image/png", b"png-a".to_vec())
.await
.unwrap();
service
.put_blob(&ws_id, "blob-b", "image/png", b"png-b".to_vec())
.await
.unwrap();
// 1. Exhaust all permits on a cold cache: manifest must fail fast with Unavailable
// and roll back its transaction immediately, releasing the DB pool connection.
let busy_guard = sem.clone().acquire_many_owned(2).await.unwrap();
let err = service
.get_readable_blob_manifest(&ws_id, &owner_id, None, 10)
.await
.expect_err("cold manifest must fail fast when decode permits are exhausted");
assert!(matches!(err, DomainError::Unavailable(_)), "got: {err:?}");
assert_eq!(sem.available_permits(), 0);
let one: i32 = sqlx::query_scalar("SELECT 1").fetch_one(db.pool()).await.unwrap();
assert_eq!(one, 1, "DB connection must be returned promptly after rollback");
// 2. Release permits and verify cursor pagination (limit = 1) returns all entries.
drop(busy_guard);
let page1 = service
.get_readable_blob_manifest(&ws_id, &owner_id, None, 1)
.await
.expect("page 1 must succeed once permits are free");
assert_eq!(page1.entries.len(), 1);
assert_eq!(page1.entries[0].key, "blob-a");
let cursor = page1.next_cursor.expect("page 1 must return next_cursor");
let page2 = service
.get_readable_blob_manifest(&ws_id, &owner_id, Some(&cursor), 1)
.await
.expect("page 2 must succeed");
assert_eq!(page2.entries.len(), 1);
assert_eq!(page2.entries[0].key, "blob-b");
assert!(page2.next_cursor.is_none());
// 3. Exhaust permits again: warm cache hits must succeed without needing any decode permit.
let busy_guard_again = sem.clone().acquire_many_owned(2).await.unwrap();
let warm = service
.get_readable_blob_manifest(&ws_id, &owner_id, None, 10)
.await
.expect("warm cache manifest must succeed even when decode permits are exhausted");
assert_eq!(
warm.entries.iter().map(|e| e.key.as_str()).collect::<Vec<_>>(),
vec!["blob-a", "blob-b"]
);
drop(busy_guard_again);
});
}
@@ -0,0 +1,513 @@
//! Pure `y_octo 0.4` extractors and transactional persistence helpers for
//! workspace root metadata (`name`, `avatar_key`) and page metadata
//! (`title`, `summary`), aligned with `affine_doc_loader`.
use std::collections::{BTreeMap, HashSet};
use std::sync::Arc;
use server_types::DomainError;
use sqlx::{Postgres, Transaction};
use y_octo::{ReadError, ReadMap, ReadValue};
use crate::acl::{ReservedDocClass, classify_reserved_doc};
use crate::doc_sharing::is_empty_doc_bin;
use crate::yjs_read::{load_yjs_doc, load_yjs_doc_with_limits, merge_update_parts_bounded};
pub const DEFAULT_MAX_SUMMARY_LENGTH: usize = 150;
/// Dedicated read limits for workspace lifecycle migration, aligned 1:1 with
/// `packages/backend/native/src/doc/mod.rs`.
pub 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,
};
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum LifecycleRootMigrationOutcome {
Completed {
root_status: &'static str,
pages: Vec<(String, bool)>,
},
ResourceLimit(String),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LegacyRootPageEntry {
pub doc_id: String,
pub trashed: bool,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum LegacyRootDecodeError {
ResourceLimit(String),
InvalidMetadata(String),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WorkspaceDocMeta {
pub name: Option<String>,
pub avatar_key: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PageDocMeta {
pub title: String,
pub summary: String,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ParsedDocMeta {
None,
Workspace(WorkspaceDocMeta),
Page(PageDocMeta),
}
/// Strips NUL (`\0`) bytes so valid Yjs text never fails PostgreSQL `TEXT`
/// inserts with SQLSTATE `22021`.
pub fn sanitize_pg_text(value: String) -> String {
if value.contains('\0') {
value.replace('\0', "")
} else {
value
}
}
/// Extracts legacy `{ id, trash }` entries from a workspace root doc's
/// `meta.pages` array under bounded `ReadLimits` without any unbounded `Doc`
/// fallback.
pub fn extract_legacy_root_pages_with_limits(
bytes: &[u8],
limits: y_octo::ReadLimits,
) -> Result<Vec<LegacyRootPageEntry>, LegacyRootDecodeError> {
if is_empty_doc_bin(bytes) {
return Ok(Vec::new());
}
let doc = load_yjs_doc_with_limits(Arc::<[u8]>::from(bytes), limits).map_err(|err| match err {
ReadError::ResourceLimit(detail) => LegacyRootDecodeError::ResourceLimit(detail.to_owned()),
other => LegacyRootDecodeError::InvalidMetadata(other.to_string()),
})?;
Ok(extract_legacy_root_pages_from_read_doc(&doc))
}
/// Filters extracted legacy root pages to ordinary workspace documents and
/// deduplicates by `doc_id` (clearing trash state when duplicate entries exist).
pub fn dedup_ordinary_legacy_root_pages(
workspace_id: &str,
pages: impl IntoIterator<Item = LegacyRootPageEntry>,
) -> Vec<(String, bool)> {
let mut unique = BTreeMap::<String, Option<bool>>::new();
for page in pages {
if classify_reserved_doc(workspace_id, &page.doc_id) == ReservedDocClass::Ordinary {
unique
.entry(page.doc_id)
.and_modify(|state| *state = None)
.or_insert(Some(page.trashed));
}
}
unique
.into_iter()
.filter_map(|(id, state)| state.map(|is_trashed| (id, is_trashed)))
.collect()
}
/// Checks total stored byte size of a workspace root doc (`snapshots` +
/// `updates`) before loading any `blob` column. Returns `Ok(Err(detail))` when
/// total bytes exceed `max_input_bytes`.
pub async fn check_lifecycle_root_bytes_in(
tx: &mut Transaction<'_, Postgres>,
workspace_id: &str,
max_input_bytes: usize,
) -> Result<Result<usize, String>, DomainError> {
let total: i64 = sqlx::query_scalar(
"SELECT COALESCE((SELECT octet_length(blob)::bigint FROM snapshots WHERE workspace_id = $1 AND guid = $1), 0) \
+ COALESCE((SELECT COALESCE(SUM(octet_length(blob)), 0)::bigint FROM updates WHERE workspace_id = $1 AND guid = $1), 0)",
)
.bind(workspace_id)
.fetch_one(&mut **tx)
.await
.map_err(|err| DomainError::Internal(format!("measure workspace lifecycle root doc size: {err}")))?;
let total_usize = usize::try_from(total).unwrap_or(usize::MAX);
if total_usize > max_input_bytes {
Ok(Err(format!(
"input bytes {total_usize} exceeds limit {max_input_bytes}"
)))
} else {
Ok(Ok(total_usize))
}
}
/// Merges and decodes a workspace root doc's legacy `meta.pages` under bounded
/// `limits`, separating recoverable `ResourceLimit` failures from terminal
/// `absent` / `invalid_binary` / `invalid_metadata` / `decoded` states.
pub fn merge_and_decode_lifecycle_root_pages(
workspace_id: &str,
snapshot: Option<Vec<u8>>,
updates: Vec<Vec<u8>>,
limits: y_octo::ReadLimits,
) -> LifecycleRootMigrationOutcome {
if snapshot.is_none() && updates.is_empty() {
return LifecycleRootMigrationOutcome::Completed {
root_status: "absent",
pages: Vec::new(),
};
}
let parts: Vec<Vec<u8>> = snapshot.into_iter().chain(updates).filter(|b| !b.is_empty()).collect();
if parts.is_empty() {
return LifecycleRootMigrationOutcome::Completed {
root_status: "decoded",
pages: Vec::new(),
};
}
let merged = match merge_update_parts_bounded(parts, limits.max_input_bytes) {
Ok(Some(merged)) => merged,
Ok(None) => {
return LifecycleRootMigrationOutcome::ResourceLimit(format!(
"merged root binary exceeds limit {}",
limits.max_input_bytes
));
}
Err(_) => {
return LifecycleRootMigrationOutcome::Completed {
root_status: "invalid_binary",
pages: Vec::new(),
};
}
};
match extract_legacy_root_pages_with_limits(&merged, limits) {
Ok(pages) => LifecycleRootMigrationOutcome::Completed {
root_status: "decoded",
pages: dedup_ordinary_legacy_root_pages(workspace_id, pages),
},
Err(LegacyRootDecodeError::InvalidMetadata(_)) => LifecycleRootMigrationOutcome::Completed {
root_status: "invalid_metadata",
pages: Vec::new(),
},
Err(LegacyRootDecodeError::ResourceLimit(detail)) => LifecycleRootMigrationOutcome::ResourceLimit(detail),
}
}
fn push_legacy_root_page(out: &mut Vec<LegacyRootPageEntry>, doc_id: &str, trashed: bool) {
if !doc_id.trim().is_empty() {
out.push(LegacyRootPageEntry {
doc_id: doc_id.to_owned(),
trashed,
});
}
}
fn push_legacy_root_page_from_read_any(out: &mut Vec<LegacyRootPageEntry>, 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_legacy_root_page(out, doc_id, trashed);
}
}
fn extract_legacy_root_pages_from_read_doc(doc: &y_octo::ReadDoc) -> Vec<LegacyRootPageEntry> {
let mut pages_out = Vec::new();
let Some(meta) = doc.map("meta") else {
return pages_out;
};
match meta.get("pages") {
Some(ReadValue::Array(pages)) => {
for entry in pages.iter() {
match entry {
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_legacy_root_page(&mut pages_out, doc_id, trashed);
}
}
ReadValue::Any(any) => push_legacy_root_page_from_read_any(&mut pages_out, &any),
_ => {}
}
}
}
Some(ReadValue::Any(any)) => {
if let Some(entries) = any.array() {
for entry in entries {
push_legacy_root_page_from_read_any(&mut pages_out, &entry);
}
}
}
_ => {}
}
pages_out
}
pub fn parse_workspace_doc_content(bin: &[u8]) -> Result<Option<WorkspaceDocMeta>, ReadError> {
if is_empty_doc_bin(bin) {
return Ok(None);
}
let doc = load_yjs_doc(Arc::<[u8]>::from(bin))?;
let Some(meta) = doc.map("meta") else {
return Ok(None);
};
if meta.is_empty() && doc.array("meta").is_some_and(|arr| !arr.is_empty()) {
return Ok(None);
}
let name = read_string_field(meta, "name").map(sanitize_pg_text);
let avatar_key = read_string_field(meta, "avatar").map(sanitize_pg_text);
Ok(Some(WorkspaceDocMeta { name, avatar_key }))
}
pub fn parse_page_doc_content(bin: &[u8], max_summary_length: usize) -> Result<Option<PageDocMeta>, ReadError> {
if is_empty_doc_bin(bin) {
return Ok(None);
}
let doc = load_yjs_doc(Arc::<[u8]>::from(bin))?;
let Some(blocks) = doc.map("blocks") else {
return Ok(None);
};
let mut root_id = None;
for (key, value) in blocks.iter() {
let Some(block) = value.as_map() else {
continue;
};
if read_string_field(block, "sys:flavour").as_deref() == Some("affine:page") {
root_id = Some(read_string_field(block, "sys:id").unwrap_or_else(|| key.to_owned()));
break;
}
}
let Some(root_id) = root_id else {
return Ok(None);
};
let Some(root_block) = blocks.get(&root_id).and_then(ReadValue::as_map) else {
return Ok(None);
};
let title = sanitize_pg_text(read_string_field(root_block, "prop:title").unwrap_or_default());
let mut summary = String::new();
let mut remaining = max_summary_length as isize;
let mut stack = vec![root_id.clone()];
let mut visited = HashSet::from([root_id]);
while let Some(block_id) = stack.pop() {
if remaining <= 0 {
break;
}
let Some(block) = blocks.get(&block_id).and_then(ReadValue::as_map) else {
continue;
};
let flavour = read_string_field(block, "sys:flavour");
match flavour.as_deref() {
Some("affine:page" | "affine:note") => {
push_children(block, &mut stack, &mut visited);
}
Some("affine:paragraph" | "affine:list" | "affine:code") => {
if remaining > 0 {
append_text(block, &mut summary, &mut remaining);
}
push_children(block, &mut stack, &mut visited);
}
_ => {}
}
}
Ok(Some(PageDocMeta {
title,
summary: sanitize_pg_text(summary),
}))
}
pub fn parse_doc_metadata(workspace_id: &str, doc_id: &str, bin: &[u8]) -> Result<ParsedDocMeta, ReadError> {
match classify_reserved_doc(workspace_id, doc_id) {
ReservedDocClass::WorkspaceRoot => Ok(
parse_workspace_doc_content(bin)?
.map(ParsedDocMeta::Workspace)
.unwrap_or(ParsedDocMeta::None),
),
ReservedDocClass::Ordinary => Ok(
parse_page_doc_content(bin, DEFAULT_MAX_SUMMARY_LENGTH)?
.map(ParsedDocMeta::Page)
.unwrap_or(ParsedDocMeta::None),
),
ReservedDocClass::WorkspaceSystem | ReservedDocClass::UserPrivate { .. } | ReservedDocClass::Invalid => {
Ok(ParsedDocMeta::None)
}
}
}
pub async fn upsert_page_metadata_in(
tx: &mut Transaction<'_, Postgres>,
workspace_id: &str,
page_id: &str,
meta: &PageDocMeta,
) -> Result<(), sqlx::Error> {
sqlx::query(
r#"INSERT INTO workspace_pages (workspace_id, page_id, title, summary)
SELECT $1, $2, $3, $4
WHERE EXISTS (SELECT 1 FROM workspaces WHERE id = $1)
AND NOT EXISTS (
SELECT 1 FROM workspace_pages
WHERE workspace_id = $1 AND page_id = $2 AND lifecycle_state::text = 'deleted'
)
ON CONFLICT (workspace_id, page_id) DO UPDATE
SET title = EXCLUDED.title,
summary = EXCLUDED.summary
WHERE workspace_pages.lifecycle_state IS DISTINCT FROM 'deleted'
AND (
workspace_pages.title IS DISTINCT FROM EXCLUDED.title
OR workspace_pages.summary IS DISTINCT FROM EXCLUDED.summary
)"#,
)
.bind(workspace_id)
.bind(page_id)
.bind(&meta.title)
.bind(&meta.summary)
.execute(&mut **tx)
.await?;
Ok(())
}
pub async fn upsert_page_title_in(
tx: &mut Transaction<'_, Postgres>,
workspace_id: &str,
page_id: &str,
title: &str,
) -> Result<(), sqlx::Error> {
let clean_title = sanitize_pg_text(title.to_owned());
sqlx::query(
r#"INSERT INTO workspace_pages (workspace_id, page_id, title)
SELECT $1, $2, $3
WHERE EXISTS (SELECT 1 FROM workspaces WHERE id = $1)
AND NOT EXISTS (
SELECT 1 FROM workspace_pages
WHERE workspace_id = $1 AND page_id = $2 AND lifecycle_state::text = 'deleted'
)
ON CONFLICT (workspace_id, page_id) DO UPDATE
SET title = EXCLUDED.title
WHERE workspace_pages.lifecycle_state IS DISTINCT FROM 'deleted'
AND workspace_pages.title IS DISTINCT FROM EXCLUDED.title"#,
)
.bind(workspace_id)
.bind(page_id)
.bind(&clean_title)
.execute(&mut **tx)
.await?;
Ok(())
}
fn read_string_field(map: ReadMap<'_>, key: &str) -> Option<String> {
match map.get(key)? {
ReadValue::Any(any) => any.as_str().map(str::to_owned),
ReadValue::Text(text) => Some(text.to_string()),
_ => None,
}
}
fn push_children(block: ReadMap<'_>, stack: &mut Vec<String>, visited: &mut HashSet<String>) {
if let Some(children) = block.get("sys:children").and_then(ReadValue::as_array) {
let mut pending = Vec::new();
for child in children.iter() {
if let Some(child_id) = child.as_any().and_then(|a| a.as_str())
&& visited.insert(child_id.to_owned())
{
pending.push(child_id.to_owned());
}
}
for child_id in pending.into_iter().rev() {
stack.push(child_id);
}
}
}
fn append_text(block: ReadMap<'_>, summary: &mut String, remaining: &mut isize) {
let content = read_string_field(block, "prop:text");
if let Some(content) = content {
let len = content.encode_utf16().count();
summary.push_str(&content);
*remaining -= len as isize;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_workspace_and_page_doc_content_recover_incomplete_snapshot_and_sanitize_nul() {
// 1. Workspace root doc with client clock gap (IncompleteSnapshot).
let root_c1 = y_octo::DocOptions::new().with_client_id(1).build();
let mut meta = root_c1.get_or_create_map("meta").unwrap();
meta
.insert("name".to_owned(), y_octo::Any::String("WS\0Clean".into()))
.unwrap();
meta
.insert("avatar".to_owned(), y_octo::Any::String("av\0-1".into()))
.unwrap();
let mut root_c2 = y_octo::DocOptions::new().with_client_id(2).build();
let mut other = root_c2.get_or_create_map("other").unwrap();
other.insert("a".to_owned(), y_octo::Any::String("1".into())).unwrap();
let sv_c2 = root_c2.get_state_vector();
other.insert("b".to_owned(), y_octo::Any::String("2".into())).unwrap();
root_c2
.apply_update_from_binary_v1(root_c1.encode_update_v1().unwrap())
.unwrap();
let root_delta = root_c2.encode_state_as_update_v1(&sv_c2).unwrap();
assert!(matches!(
y_octo::ReadDoc::from_full_update_v1(root_delta.clone()),
Err(ReadError::IncompleteSnapshot(_))
));
let ws_meta = parse_workspace_doc_content(&root_delta)
.expect("incomplete snapshot workspace root must decode")
.expect("workspace meta must be present");
assert_eq!(ws_meta.name.as_deref(), Some("WSClean"));
assert_eq!(ws_meta.avatar_key.as_deref(), Some("av-1"));
// 2. Page doc with client clock gap (IncompleteSnapshot).
let page_c1 = y_octo::DocOptions::new().with_client_id(11).build();
let mut blocks = page_c1.get_or_create_map("blocks").unwrap();
let mut page = page_c1.create_map().unwrap();
page
.insert("sys:id".to_owned(), y_octo::Any::String("p1".into()))
.unwrap();
page
.insert("sys:flavour".to_owned(), y_octo::Any::String("affine:page".into()))
.unwrap();
let mut title = page_c1.create_text().unwrap();
title.insert(0, "Title\0Nul").unwrap();
page.insert("prop:title".to_owned(), title).unwrap();
let mut children = page_c1.create_array().unwrap();
children.push(y_octo::Any::String("para1".into())).unwrap();
page.insert("sys:children".to_owned(), children).unwrap();
blocks.insert("p1".to_owned(), page).unwrap();
let mut para = page_c1.create_map().unwrap();
para
.insert("sys:id".to_owned(), y_octo::Any::String("para1".into()))
.unwrap();
para
.insert("sys:flavour".to_owned(), y_octo::Any::String("affine:paragraph".into()))
.unwrap();
let mut text = page_c1.create_text().unwrap();
text.insert(0, "Body\0Text").unwrap();
para.insert("prop:text".to_owned(), text).unwrap();
blocks.insert("para1".to_owned(), para).unwrap();
let mut page_c2 = y_octo::DocOptions::new().with_client_id(12).build();
let mut scratch = page_c2.get_or_create_map("scratch").unwrap();
scratch.insert("x".to_owned(), y_octo::Any::String("1".into())).unwrap();
let sv_page_c2 = page_c2.get_state_vector();
scratch.insert("y".to_owned(), y_octo::Any::String("2".into())).unwrap();
page_c2
.apply_update_from_binary_v1(page_c1.encode_update_v1().unwrap())
.unwrap();
let page_delta = page_c2.encode_state_as_update_v1(&sv_page_c2).unwrap();
assert!(matches!(
y_octo::ReadDoc::from_full_update_v1(page_delta.clone()),
Err(ReadError::IncompleteSnapshot(_))
));
let page_meta = parse_page_doc_content(&page_delta, DEFAULT_MAX_SUMMARY_LENGTH)
.expect("incomplete snapshot page must decode")
.expect("page meta must be present");
assert_eq!(page_meta.title, "TitleNul");
assert_eq!(page_meta.summary, "BodyText");
}
}
File diff suppressed because it is too large. Load diff
+526 -4
View File
@@ -14,6 +14,7 @@ use sqlx::{Postgres, Row, Transaction};
use tokio::sync::Semaphore;
use crate::acl::load_workspace_docs_access_in;
use crate::doc_meta::{ParsedDocMeta, parse_doc_metadata, upsert_page_metadata_in};
use crate::doc_sharing::{DocSharingService, is_empty_doc_bin};
#[derive(Clone, Debug)]
@@ -433,6 +434,7 @@ struct Phase2Merged {
final_blob: Vec<u8>,
prev_snapshot_is_empty: bool,
blob_changed: bool,
parsed_meta: ParsedDocMeta,
}
enum Phase3Outcome {
@@ -525,6 +527,8 @@ where
}
merge_inputs.extend(phase1.updates.iter().map(|u| u.blob.clone()));
let prev_blob = phase1.snapshot.as_ref().map(|s| s.blob.clone());
let ws_owned = workspace_id.to_owned();
let doc_owned = doc_id.to_owned();
run_blocking_with_merge_permit(compaction_merge_semaphore(), move || {
let final_blob = if merge_inputs.len() == 1 {
merge_inputs.remove(0)
@@ -535,10 +539,23 @@ where
};
let prev_snapshot_is_empty = prev_blob.as_deref().is_none_or(is_empty_doc_bin);
let blob_changed = prev_blob.as_deref().is_none_or(|prev| prev != final_blob.as_slice());
let parsed_meta = match parse_doc_metadata(&ws_owned, &doc_owned, &final_blob) {
Ok(meta) => meta,
Err(err) => {
tracing::warn!(
workspace_id = %ws_owned,
doc_id = %doc_owned,
error = %err,
"skipping document metadata projection due to decode error"
);
ParsedDocMeta::None
}
};
Ok(Phase2Merged {
final_blob,
prev_snapshot_is_empty,
blob_changed,
parsed_meta,
})
})
.await?
@@ -881,6 +898,14 @@ async fn commit_compaction_phase3(
return Err(Phase3Error::CasMismatch);
}
let has_remaining_updates: bool =
sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM updates WHERE workspace_id = $1 AND guid = $2)")
.bind(workspace_id)
.bind(doc_id)
.fetch_one(&mut **tx)
.await
.map_err(map_phase3_sqlx("check remaining updates after compaction"))?;
sqlx::query(
r#"UPDATE doc_blob_ref_projections
SET status = 'pending',
@@ -917,11 +942,31 @@ async fn commit_compaction_phase3(
}
if workspace_id == doc_id {
sqlx::query("UPDATE workspaces SET last_check_embeddings = '1970-01-01T00:00:00Z' WHERE id = $1")
.bind(workspace_id)
.execute(&mut **tx)
let (name, avatar_key) = if has_remaining_updates {
(None, None)
} else {
match &phase2.parsed_meta {
ParsedDocMeta::Workspace(meta) => (meta.name.as_deref(), meta.avatar_key.as_deref()),
_ => (None, None),
}
};
sqlx::query(
r#"UPDATE workspaces
SET last_check_embeddings = '1970-01-01T00:00:00Z',
name = COALESCE($2, name),
avatar_key = COALESCE($3, avatar_key)
WHERE id = $1"#,
)
.bind(workspace_id)
.bind(name)
.bind(avatar_key)
.execute(&mut **tx)
.await
.map_err(map_phase3_sqlx("update workspace compaction metadata"))?;
} else if !has_remaining_updates && let ParsedDocMeta::Page(meta) = &phase2.parsed_meta {
upsert_page_metadata_in(tx, workspace_id, doc_id, meta)
.await
.map_err(map_phase3_sqlx("reset workspace last_check_embeddings"))?;
.map_err(map_phase3_sqlx("backfill compacted doc metadata"))?;
}
let mut history_created = false;
@@ -1446,4 +1491,481 @@ mod tests {
});
drop(lease);
}
fn build_synthetic_root_doc(name: &str, avatar: &str) -> Vec<u8> {
let doc = y_octo::Doc::with_client(401);
let mut meta = doc.get_or_create_map("meta").unwrap();
meta
.insert("name".to_owned(), y_octo::Any::String(name.to_owned()))
.unwrap();
meta
.insert("avatar".to_owned(), y_octo::Any::String(avatar.to_owned()))
.unwrap();
doc.encode_update_v1().unwrap()
}
fn build_synthetic_page_doc(title: &str, paragraphs: &[&str]) -> Vec<u8> {
let doc = y_octo::Doc::with_client(402);
let mut blocks = doc.get_or_create_map("blocks").unwrap();
let mut page = doc.create_map().unwrap();
page
.insert("sys:id".to_owned(), y_octo::Any::String("page-1".into()))
.unwrap();
page
.insert("sys:flavour".to_owned(), y_octo::Any::String("affine:page".into()))
.unwrap();
let mut title_text = doc.create_text().unwrap();
title_text.insert(0, title).unwrap();
page.insert("prop:title".to_owned(), title_text).unwrap();
let mut page_children = doc.create_array().unwrap();
page_children.push(y_octo::Any::String("note-1".into())).unwrap();
page.insert("sys:children".to_owned(), page_children).unwrap();
blocks.insert("page-1".to_owned(), page).unwrap();
let mut note = doc.create_map().unwrap();
note
.insert("sys:id".to_owned(), y_octo::Any::String("note-1".into()))
.unwrap();
note
.insert("sys:flavour".to_owned(), y_octo::Any::String("affine:note".into()))
.unwrap();
let mut note_children = doc.create_array().unwrap();
// Nested affine:list (parent -> child) before top-level paragraphs verifies pre-order DFS order.
note_children.push(y_octo::Any::String("list-parent".into())).unwrap();
let mut list_parent = doc.create_map().unwrap();
list_parent
.insert("sys:id".to_owned(), y_octo::Any::String("list-parent".into()))
.unwrap();
list_parent
.insert("sys:flavour".to_owned(), y_octo::Any::String("affine:list".into()))
.unwrap();
let mut lp_text = doc.create_text().unwrap();
lp_text.insert(0, "L1:").unwrap();
list_parent.insert("prop:text".to_owned(), lp_text).unwrap();
let mut lp_children = doc.create_array().unwrap();
lp_children.push(y_octo::Any::String("list-child".into())).unwrap();
list_parent.insert("sys:children".to_owned(), lp_children).unwrap();
blocks.insert("list-parent".to_owned(), list_parent).unwrap();
let mut list_child = doc.create_map().unwrap();
list_child
.insert("sys:id".to_owned(), y_octo::Any::String("list-child".into()))
.unwrap();
list_child
.insert("sys:flavour".to_owned(), y_octo::Any::String("affine:list".into()))
.unwrap();
let mut lc_text = doc.create_text().unwrap();
lc_text.insert(0, "L1a;").unwrap();
list_child.insert("prop:text".to_owned(), lc_text).unwrap();
blocks.insert("list-child".to_owned(), list_child).unwrap();
for (idx, body) in paragraphs.iter().enumerate() {
let para_id = format!("para-{idx}");
note_children.push(y_octo::Any::String(para_id.clone())).unwrap();
let mut para = doc.create_map().unwrap();
para
.insert("sys:id".to_owned(), y_octo::Any::String(para_id.clone()))
.unwrap();
para
.insert("sys:flavour".to_owned(), y_octo::Any::String("affine:paragraph".into()))
.unwrap();
let mut p_text = doc.create_text().unwrap();
p_text.insert(0, body).unwrap();
para.insert("prop:text".to_owned(), p_text).unwrap();
blocks.insert(para_id, para).unwrap();
}
note.insert("sys:children".to_owned(), note_children).unwrap();
blocks.insert("note-1".to_owned(), note).unwrap();
doc.encode_update_v1().unwrap()
}
#[test]
fn compaction_backfills_workspace_and_page_metadata_without_touching_reserved_or_deleted_docs() {
let cluster = test_db_harness::pg::PgCluster::from_env_or_docker().expect("test postgres cluster");
let migrations_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../server/migrations");
let migrations = test_db_harness::migrations::MigrationSet::load(&migrations_dir).expect("load migrations");
let template = cluster.ensure_template(&migrations).expect("ensure template");
let lease = cluster
.lease(&template, test_db_harness::pg::DEFAULT_LEASE_TTL)
.expect("lease test db");
let db_url = lease.url().to_owned();
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("runtime");
rt.block_on(async move {
let db = ServerDb::connect(DbConfig {
database_url: db_url,
channel: "canary".into(),
role: server_types::ServerRole::Allinone,
selfhosted: true,
max_connections: 4,
statement_timeout_ms: 5_000,
tier_permits: [8, 4, 2, 2],
})
.await
.expect("connect db");
sqlx::raw_sql("DROP SCHEMA public CASCADE; CREATE SCHEMA public;")
.execute(db.pool())
.await
.expect("reset schema");
db.ensure_schema_ready().await.expect("ensure schema");
let user_id = Uuid::new_v4().to_string();
let ws_compact = format!("ws-compact-{}", Uuid::new_v4().simple());
sqlx::query("INSERT INTO users (id, name, email) VALUES ($1, 'Author', 'meta@example.com')")
.bind(&user_id)
.execute(db.pool())
.await
.unwrap();
sqlx::query("INSERT INTO workspaces (id) VALUES ($1)")
.bind(&ws_compact)
.execute(db.pool())
.await
.unwrap();
let t0 = Utc::now() - Duration::seconds(60);
let root_bin = build_synthetic_root_doc("Synthetic Workspace", "avatar-key-1");
let para1 = "a".repeat(120);
let para2 = "b".repeat(60);
let para3 = "c".repeat(40);
let page_bin = build_synthetic_page_doc("Synthetic Page Title", &[&para1, &para2, &para3]);
let db_sys_doc = format!("db${ws_compact}$docProperties");
let userdata_doc = format!("userdata${user_id}${ws_compact}$favorite");
// Pre-populate a deleted page row that must never be resurrected.
sqlx::query(
"INSERT INTO workspace_pages (workspace_id, page_id, title, summary, lifecycle_state)
VALUES ($1, 'doc-deleted', 'Old Deleted', 'old', 'deleted')",
)
.bind(&ws_compact)
.execute(db.pool())
.await
.unwrap();
for (guid, blob) in [
(ws_compact.as_str(), root_bin.as_slice()),
("doc-ordinary", page_bin.as_slice()),
("doc-deleted", page_bin.as_slice()),
(db_sys_doc.as_str(), page_bin.as_slice()),
(userdata_doc.as_str(), page_bin.as_slice()),
] {
sqlx::query(
"INSERT INTO updates (workspace_id, guid, blob, created_at, created_by)
VALUES ($1, $2, $3, $4, $5)",
)
.bind(&ws_compact)
.bind(guid)
.bind(blob)
.bind(t0)
.bind(&user_id)
.execute(db.pool())
.await
.unwrap();
}
let quota = server_spi::CommunityQuotaGate::new();
let compacted = compact_pending_docs_batch(&db, &quota, 100, 500, 600_000, || false)
.await
.expect("compact batch");
assert_eq!(compacted, 4, "deleted doc is skipped; 4 active docs compact");
let (ws_name, ws_avatar): (Option<String>, Option<String>) =
sqlx::query_as("SELECT name, avatar_key FROM workspaces WHERE id = $1")
.bind(&ws_compact)
.fetch_one(db.pool())
.await
.unwrap();
assert_eq!(ws_name.as_deref(), Some("Synthetic Workspace"));
assert_eq!(ws_avatar.as_deref(), Some("avatar-key-1"));
// Pre-order DFS: L1: (3) + L1a; (4) + para1 (120) + para2 (60) -> remaining drops below 0, so para3 is NOT appended.
let expected_summary = format!("L1:L1a;{para1}{para2}");
let (page_title, page_summary): (Option<String>, Option<String>) =
sqlx::query_as("SELECT title, summary FROM workspace_pages WHERE workspace_id = $1 AND page_id = 'doc-ordinary'")
.bind(&ws_compact)
.fetch_one(db.pool())
.await
.unwrap();
assert_eq!(page_title.as_deref(), Some("Synthetic Page Title"));
assert_eq!(page_summary.as_deref(), Some(expected_summary.as_str()));
// Reserved docs must not appear in workspace_pages.
let reserved_count: i64 = sqlx::query_scalar(
"SELECT COUNT(*)::bigint FROM workspace_pages WHERE workspace_id = $1 AND page_id = ANY($2)",
)
.bind(&ws_compact)
.bind(vec![ws_compact.clone(), db_sys_doc.clone(), userdata_doc.clone()])
.fetch_one(db.pool())
.await
.unwrap();
assert_eq!(reserved_count, 0);
// Deleted doc remains deleted with original metadata untouched.
let (del_state, del_title): (String, Option<String>) = sqlx::query_as(
"SELECT lifecycle_state::text, title FROM workspace_pages WHERE workspace_id = $1 AND page_id = 'doc-deleted'",
)
.bind(&ws_compact)
.fetch_one(db.pool())
.await
.unwrap();
assert_eq!(del_state, "deleted");
assert_eq!(del_title.as_deref(), Some("Old Deleted"));
// Second compaction on doc-ordinary must preserve existing mode and published_at.
let pub_ts = Utc::now() - Duration::hours(1);
sqlx::query(
"UPDATE workspace_pages SET mode = 1, published_at = $2 WHERE workspace_id = $1 AND page_id = 'doc-ordinary'",
)
.bind(&ws_compact)
.bind(pub_ts)
.execute(db.pool())
.await
.unwrap();
let mut updated_doc = y_octo::Doc::with_client(403);
updated_doc.apply_update_from_binary_v1(&page_bin).unwrap();
let sv = updated_doc.get_state_vector();
{
let blocks = updated_doc.get_or_create_map("blocks").unwrap();
if let Some(y_octo::Value::Map(mut page)) = blocks.get("page-1") {
let mut new_title = updated_doc.create_text().unwrap();
new_title.insert(0, "Updated Page Title").unwrap();
page.insert("prop:title".to_owned(), new_title).unwrap();
}
if let Some(y_octo::Value::Map(mut note)) = blocks.get("note-1") {
let mut new_children = updated_doc.create_array().unwrap();
new_children.push(y_octo::Any::String("para-fresh".into())).unwrap();
note.insert("sys:children".to_owned(), new_children).unwrap();
}
let mut fresh_para = updated_doc.create_map().unwrap();
fresh_para
.insert("sys:id".to_owned(), y_octo::Any::String("para-fresh".into()))
.unwrap();
fresh_para
.insert(
"sys:flavour".to_owned(),
y_octo::Any::String("affine:paragraph".into()),
)
.unwrap();
let mut fresh_text = updated_doc.create_text().unwrap();
fresh_text.insert(0, "fresh summary").unwrap();
fresh_para.insert("prop:text".to_owned(), fresh_text).unwrap();
let mut blocks = updated_doc.get_or_create_map("blocks").unwrap();
blocks.insert("para-fresh".to_owned(), fresh_para).unwrap();
}
let updated_page_bin = updated_doc.encode_state_as_update_v1(&sv).unwrap();
sqlx::query(
"INSERT INTO updates (workspace_id, guid, blob, created_at, created_by)
VALUES ($1, 'doc-ordinary', $2, $3, $4)",
)
.bind(&ws_compact)
.bind(&updated_page_bin)
.bind(Utc::now())
.bind(&user_id)
.execute(db.pool())
.await
.unwrap();
compact_pending_doc_updates(&db, &ws_compact, "doc-ordinary", 100, 0, 0)
.await
.expect("second compaction");
let (title2, summary2, mode2, pub2): (Option<String>, Option<String>, i16, Option<DateTime<Utc>>) = sqlx::query_as(
"SELECT title, summary, mode, published_at FROM workspace_pages WHERE workspace_id = $1 AND page_id = 'doc-ordinary'",
)
.bind(&ws_compact)
.fetch_one(db.pool())
.await
.unwrap();
assert_eq!(title2.as_deref(), Some("Updated Page Title"));
assert_eq!(summary2.as_deref(), Some("fresh summary"));
assert_eq!(mode2, 1);
assert!(pub2.is_some());
// Boundary 1: compacting a workspace root doc whose meta only contains pages (no name/avatar keys)
// must preserve existing workspaces.name and workspaces.avatar_key rather than wiping them to "".
let ws_preserve = format!("ws-preserve-{}", Uuid::new_v4().simple());
sqlx::query("INSERT INTO workspaces (id, name, avatar_key) VALUES ($1, 'Preset Name', 'preset-avatar')")
.bind(&ws_preserve)
.execute(db.pool())
.await
.unwrap();
let pages_only_root = {
let doc = y_octo::Doc::with_client(404);
let mut meta = doc.get_or_create_map("meta").unwrap();
let mut pages = doc.create_array().unwrap();
let mut entry = doc.create_map().unwrap();
entry
.insert("id".to_owned(), y_octo::Any::String("page-only".into()))
.unwrap();
pages.push(entry).unwrap();
meta.insert("pages".to_owned(), pages).unwrap();
doc.encode_update_v1().unwrap()
};
sqlx::query(
"INSERT INTO updates (workspace_id, guid, blob, created_at, created_by)
VALUES ($1, $1, $2, $3, $4)",
)
.bind(&ws_preserve)
.bind(&pages_only_root)
.bind(Utc::now())
.bind(&user_id)
.execute(db.pool())
.await
.unwrap();
compact_pending_doc_updates(&db, &ws_preserve, &ws_preserve, 100, 0, 0)
.await
.expect("pages-only root compaction");
let (pres_name, pres_avatar): (Option<String>, Option<String>) =
sqlx::query_as("SELECT name, avatar_key FROM workspaces WHERE id = $1")
.bind(&ws_preserve)
.fetch_one(db.pool())
.await
.unwrap();
assert_eq!(pres_name.as_deref(), Some("Preset Name"));
assert_eq!(pres_avatar.as_deref(), Some("preset-avatar"));
// Boundary 2: NUL (\0) bytes in workspace name or page title/body must be sanitized
// instead of failing PostgreSQL UTF-8 text writes with SQLSTATE 22021.
let ws_nul = format!("ws-nul-{}", Uuid::new_v4().simple());
sqlx::query("INSERT INTO workspaces (id) VALUES ($1)")
.bind(&ws_nul)
.execute(db.pool())
.await
.unwrap();
let nul_root = build_synthetic_root_doc("WS\0Nul", "av\0nul");
let nul_page = build_synthetic_page_doc("Title\0Nul", &["Body\0Nul"]);
for (guid, blob) in [(ws_nul.as_str(), nul_root.as_slice()), ("doc-nul", nul_page.as_slice())] {
sqlx::query(
"INSERT INTO updates (workspace_id, guid, blob, created_at, created_by)
VALUES ($1, $2, $3, $4, $5)",
)
.bind(&ws_nul)
.bind(guid)
.bind(blob)
.bind(Utc::now())
.bind(&user_id)
.execute(db.pool())
.await
.unwrap();
}
compact_pending_doc_updates(&db, &ws_nul, &ws_nul, 100, 0, 0)
.await
.expect("nul root compaction must succeed");
compact_pending_doc_updates(&db, &ws_nul, "doc-nul", 100, 0, 0)
.await
.expect("nul page compaction must succeed");
let (nul_ws_name, nul_ws_avatar): (Option<String>, Option<String>) =
sqlx::query_as("SELECT name, avatar_key FROM workspaces WHERE id = $1")
.bind(&ws_nul)
.fetch_one(db.pool())
.await
.unwrap();
assert_eq!(nul_ws_name.as_deref(), Some("WSNul"));
assert_eq!(nul_ws_avatar.as_deref(), Some("avnul"));
let (nul_title, nul_summary): (Option<String>, Option<String>) =
sqlx::query_as("SELECT title, summary FROM workspace_pages WHERE workspace_id = $1 AND page_id = 'doc-nul'")
.bind(&ws_nul)
.fetch_one(db.pool())
.await
.unwrap();
assert_eq!(nul_title.as_deref(), Some("TitleNul"));
assert_eq!(nul_summary.as_deref(), Some("L1:L1a;BodyNul"));
// Boundary 3: batched compaction must not overwrite newer concurrent metadata
// (for example an MCP title update) while newer updates remain in `updates`.
let ws_mono = format!("ws-mono-{}", Uuid::new_v4().simple());
sqlx::query("INSERT INTO workspaces (id) VALUES ($1)")
.bind(&ws_mono)
.execute(db.pool())
.await
.unwrap();
let initial_page = build_synthetic_page_doc("Initial Stale Title", &["stale body"]);
let t_initial = Utc::now() - Duration::seconds(30);
sqlx::query(
"INSERT INTO updates (workspace_id, guid, blob, created_at, created_by)
VALUES ($1, 'doc-mono', $2, $3, $4)",
)
.bind(&ws_mono)
.bind(&initial_page)
.bind(t_initial)
.bind(&user_id)
.execute(db.pool())
.await
.unwrap();
let concurrent_delta = {
let mut d = y_octo::Doc::with_client(405);
d.apply_update_from_binary_v1(&initial_page).unwrap();
let sv = d.get_state_vector();
if let Some(y_octo::Value::Map(mut page)) = d.get_or_create_map("blocks").unwrap().get("page-1") {
let mut new_title = d.create_text().unwrap();
new_title.insert(0, "Newer Concurrent Title").unwrap();
page.insert("prop:title".to_owned(), new_title).unwrap();
}
d.encode_state_as_update_v1(&sv).unwrap()
};
let db_hook = db.clone();
let ws_hook = ws_mono.clone();
let user_hook = user_id.clone();
let delta_hook = concurrent_delta.clone();
let mono_outcome = compact_pending_doc_updates_with_merge_hook(&db, &ws_mono, "doc-mono", 10, 0, 0, move |attempt| {
let db_hook = db_hook.clone();
let ws_hook = ws_hook.clone();
let user_hook = user_hook.clone();
let delta_hook = delta_hook.clone();
async move {
if attempt == 0 {
let mut tx = db_hook.pool().begin().await.unwrap();
sqlx::query(
"INSERT INTO updates (workspace_id, guid, blob, created_at, created_by)
VALUES ($1, 'doc-mono', $2, $3, $4)",
)
.bind(&ws_hook)
.bind(&delta_hook)
.bind(Utc::now())
.bind(&user_hook)
.execute(&mut *tx)
.await
.unwrap();
crate::doc_meta::upsert_page_title_in(&mut tx, &ws_hook, "doc-mono", "Newer Concurrent Title")
.await
.unwrap();
tx.commit().await.unwrap();
}
}
})
.await
.expect("first batched compaction must succeed");
assert!(mono_outcome.lock_acquired);
assert_eq!(mono_outcome.updates_merged, 1);
let mid_title: Option<String> =
sqlx::query_scalar("SELECT title FROM workspace_pages WHERE workspace_id = $1 AND page_id = 'doc-mono'")
.bind(&ws_mono)
.fetch_one(db.pool())
.await
.unwrap();
assert_eq!(
mid_title.as_deref(),
Some("Newer Concurrent Title"),
"partial batch compaction must not revert newer concurrent title"
);
let mono_outcome2 = compact_pending_doc_updates(&db, &ws_mono, "doc-mono", 10, 0, 0)
.await
.expect("second compaction drains remaining update");
assert_eq!(mono_outcome2.updates_merged, 1);
let final_title: Option<String> =
sqlx::query_scalar("SELECT title FROM workspace_pages WHERE workspace_id = $1 AND page_id = 'doc-mono'")
.bind(&ws_mono)
.fetch_one(db.pool())
.await
.unwrap();
assert_eq!(final_title.as_deref(), Some("Newer Concurrent Title"));
});
drop(lease);
}
}
@@ -15,6 +15,7 @@ pub mod calendar;
pub mod comments;
pub mod content_policy;
pub mod disposition;
pub mod doc_meta;
pub mod doc_sharing;
pub mod events;
pub mod histories;
@@ -24,3 +25,4 @@ pub mod safe_fetch;
pub mod selfhost_license;
pub mod users;
pub mod workspaces;
pub mod yjs_read;
+603 -116
View File
@@ -129,6 +129,7 @@ pub struct McpCredentialService {
event_bus: Arc<dyn EventBusPublisher>,
quota_gate: Option<Arc<dyn QuotaGate>>,
invalidation: Option<Arc<dyn InvalidationPublisher>>,
decode_semaphore: Arc<tokio::sync::Semaphore>,
}
impl McpCredentialService {
pub fn new(db: ServerDb, event_bus: Arc<dyn EventBusPublisher>) -> Self {
@@ -137,6 +138,7 @@ impl McpCredentialService {
event_bus,
quota_gate: None,
invalidation: None,
decode_semaphore: Arc::clone(crate::yjs_read::doc_decode_semaphore()),
}
}
pub fn with_quota_gate(mut self, quota_gate: Arc<dyn QuotaGate>) -> Self {
@@ -147,6 +149,10 @@ impl McpCredentialService {
self.invalidation = Some(invalidation);
self
}
pub fn with_decode_semaphore(mut self, semaphore: Arc<tokio::sync::Semaphore>) -> Self {
self.decode_semaphore = semaphore;
self
}
pub async fn list(&self, user_id: &str, workspace_id: &str) -> Result<Vec<McpCredentialView>, DomainError> {
let mut conn = self
.db
@@ -403,16 +409,48 @@ impl McpCredentialService {
"Reserved document cannot be accessed.".to_owned(),
));
}
let mut conn = self
let mut tx = self
.db
.acquire_tiered(WorkloadTier::InteractiveRead)
.begin_tiered(WorkloadTier::InteractiveRead)
.await
.map_err(int_err("acquire read_doc"))?;
Ok(
load_and_merge_doc_exec(&mut conn, workspace_id, doc_id)
.await?
.map(|m| extract_title_and_markdown_from_yjs(&m)),
.map_err(int_err("begin read_doc"))?;
sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
.execute(&mut **tx.tx_mut())
.await
.map_err(int_err("set repeatable read for read_doc"))?;
let parts = match crate::doc_sharing::DocSharingService::load_doc_parts_bounded_in(
tx.tx_mut(),
workspace_id,
doc_id,
MAX_MCP_DOC_BYTES,
)
.await
{
Ok(parts) => parts,
Err(ref err) if crate::doc_sharing::is_doc_parts_too_large(err) => {
let _ = tx.rollback().await;
return Err(DomainError::Validation(
"Document exceeds the 32 MiB read size limit.".to_owned(),
));
}
Err(err) => {
let _ = tx.rollback().await;
return Err(err);
}
};
let _ = tx.rollback().await;
let Some(parts) = parts else {
return Ok(None);
};
crate::yjs_read::run_with_decode_semaphore(&self.decode_semaphore, move || {
let Some(merged) = crate::yjs_read::merge_update_parts_bounded(parts, MAX_MCP_DOC_BYTES).map_err(y_err)? else {
return Err(DomainError::Validation(
"Document exceeds the 32 MiB read size limit.".to_owned(),
));
};
Ok(Some(extract_title_and_markdown_from_yjs(&merged)))
})
.await
}
pub async fn read_document_markdown(&self, workspace_id: &str, doc_id: &str) -> Result<Option<String>, DomainError> {
Ok(
@@ -505,13 +543,28 @@ impl McpCredentialService {
None => Uuid::new_v4().to_string(),
};
let is_recover = explicit_doc_id.is_some();
let new_blob = if !is_recover {
let new_doc_prepared = if !is_recover {
let (t, b) = (title.to_owned(), strip_leading_h1(body_markdown).to_owned());
Some(
tokio::task::spawn_blocking(move || build_yjs_doc_binary(&t, &b))
.await
.map_err(int_err("join build doc"))??,
)
let ws_id = workspace_id.to_owned();
let d_id = doc_id.clone();
let (blob, parsed) = crate::yjs_read::run_with_decode_semaphore(&self.decode_semaphore, move || {
let blob = build_yjs_doc_binary(&t, &b)?;
let parsed = match crate::doc_meta::parse_page_doc_content(&blob, crate::doc_meta::DEFAULT_MAX_SUMMARY_LENGTH) {
Ok(meta) => meta,
Err(err) => {
tracing::warn!(
workspace_id = %ws_id,
doc_id = %d_id,
error = %err,
"skipping document metadata projection due to decode error"
);
None
}
};
Ok((blob, parsed))
})
.await?;
Some((blob, parsed))
} else {
None
};
@@ -524,17 +577,80 @@ impl McpCredentialService {
self.assert_workspace_writable_in(tx.tx_mut(), workspace_id).await?;
lock_workspace_docs_ordered(tx.tx_mut(), workspace_id, &[&doc_id, workspace_id, &props_doc_id]).await?;
let mut pushed = Vec::new();
let (effective_title, prop_creator, prop_editor) = if is_recover {
let Some(existing) = load_and_merge_doc_exec(tx.tx_mut(), workspace_id, &doc_id).await? else {
return Err(DomainError::NotFound(format!("Doc with id {doc_id} not found.")));
let (effective_title, page_meta, prop_creator, prop_editor) = if is_recover {
let parts = match crate::doc_sharing::DocSharingService::load_doc_parts_bounded_in(
tx.tx_mut(),
workspace_id,
&doc_id,
MAX_MCP_DOC_BYTES,
)
.await
{
Ok(Some(parts)) => parts,
Ok(None) => return Err(DomainError::NotFound(format!("Doc with id {doc_id} not found."))),
Err(ref err) if crate::doc_sharing::is_doc_parts_too_large(err) => {
return Err(DomainError::Validation(
"Document exceeds the 32 MiB recovery size limit.".to_owned(),
));
}
Err(e) => return Err(e),
};
let (creator, editor) = resolve_recover_authors_in(tx.tx_mut(), workspace_id, &doc_id).await?;
let t = extract_title_from_yjs(&existing)
let ws_id = workspace_id.to_owned();
let d_id = doc_id.clone();
let parsed = match crate::yjs_read::try_run_with_decode_semaphore(&self.decode_semaphore, move || {
let Some(merged) = crate::yjs_read::merge_update_parts_bounded(parts, MAX_MCP_DOC_BYTES)
.map_err(int_err("merge mcp recover doc"))?
else {
return Err(DomainError::Validation(
"Document exceeds the 32 MiB recovery size limit.".to_owned(),
));
};
match crate::doc_meta::parse_page_doc_content(&merged, crate::doc_meta::DEFAULT_MAX_SUMMARY_LENGTH) {
Ok(meta) => Ok(meta),
Err(err) => {
tracing::warn!(
workspace_id = %ws_id,
doc_id = %d_id,
error = %err,
"aborting recover document due to decode error"
);
Err(DomainError::Validation(format!(
"Failed to decode document for recovery: {err}"
)))
}
}
})
.await?
{
Some(meta) => meta,
None => {
tracing::warn!(
workspace_id = %workspace_id,
doc_id = %doc_id,
"aborting recover document because decode permits are busy"
);
return Err(DomainError::Unavailable(
"Document decode permits are busy; please retry.".to_owned(),
));
}
};
let t = parsed
.as_ref()
.map(|m| m.title.clone())
.filter(|t| !t.trim().is_empty())
.unwrap_or_else(|| title.to_owned());
(t, creator, editor)
.unwrap_or_else(|| crate::doc_meta::sanitize_pg_text(title.to_owned()));
let meta = crate::doc_meta::PageDocMeta {
title: t.clone(),
summary: parsed.map(|m| m.summary).unwrap_or_default(),
};
(t, meta, creator, editor)
} else {
let blob = new_blob.unwrap_or_default();
let (blob, parsed) = new_doc_prepared.unwrap_or_default();
let meta = crate::doc_meta::PageDocMeta {
title: crate::doc_meta::sanitize_pg_text(title.to_owned()),
summary: parsed.map(|m| m.summary).unwrap_or_default(),
};
sqlx::query(
r#"INSERT INTO snapshots (workspace_id, guid, blob, size, created_at, updated_at, created_by, updated_by)
VALUES ($1, $2, $3, octet_length($3), clock_timestamp(), clock_timestamp(), $4, $4)"#,
@@ -547,7 +663,12 @@ impl McpCredentialService {
.await
.map_err(int_err("insert mcp document snapshot"))?;
pushed.push((doc_id.clone(), blob));
(title.to_owned(), Some(user_id.to_owned()), Some(user_id.to_owned()))
(
title.to_owned(),
meta,
Some(user_id.to_owned()),
Some(user_id.to_owned()),
)
};
let now_ms = Utc::now().timestamp_millis();
if !is_doc_lifecycle_active_in(tx.tx_mut()).await?
@@ -579,7 +700,9 @@ impl McpCredentialService {
{
pushed.push((props_doc_id, pd));
}
upsert_workspace_page_in(tx.tx_mut(), workspace_id, &doc_id, &effective_title).await?;
crate::doc_meta::upsert_page_metadata_in(tx.tx_mut(), workspace_id, &doc_id, &page_meta)
.await
.map_err(db_err)?;
tx.commit().await.map_err(int_err("commit create_document"))?;
self.notify_doc_updates(workspace_id, user_id, pushed).await;
Ok(doc_id)
@@ -610,12 +733,33 @@ impl McpCredentialService {
vec![doc_id, &props_doc_id]
};
lock_workspace_docs_ordered(tx.tx_mut(), workspace_id, &lock_ids).await?;
let Some(merged) = load_and_merge_doc_exec(tx.tx_mut(), workspace_id, doc_id).await? else {
return Ok(false);
let parts = match crate::doc_sharing::DocSharingService::load_doc_parts_bounded_in(
tx.tx_mut(),
workspace_id,
doc_id,
MAX_MCP_DOC_BYTES,
)
.await
{
Ok(Some(parts)) => parts,
Ok(None) => return Ok(false),
Err(ref err) if crate::doc_sharing::is_doc_parts_too_large(err) => {
return Err(DomainError::Validation(
"Document exceeds the 32 MiB update size limit.".to_owned(),
));
}
Err(err) => return Err(err),
};
let delta = tokio::task::spawn_blocking(move || mutate(merged))
.await
.map_err(int_err("join mutate doc"))??;
let delta = tokio::task::spawn_blocking(move || {
let Some(merged) = crate::yjs_read::merge_update_parts_bounded(parts, MAX_MCP_DOC_BYTES).map_err(y_err)? else {
return Err(DomainError::Validation(
"Document exceeds the 32 MiB update size limit.".to_owned(),
));
};
mutate(merged)
})
.await
.map_err(int_err("join mutate doc"))??;
let mut pushed = Vec::new();
if !delta.is_empty() {
append_doc_update_in(tx.tx_mut(), workspace_id, doc_id, &delta, user_id).await?;
@@ -629,7 +773,9 @@ impl McpCredentialService {
{
pushed.push((workspace_id.to_owned(), rd));
}
upsert_workspace_page_in(tx.tx_mut(), workspace_id, doc_id, title).await?;
crate::doc_meta::upsert_page_title_in(tx.tx_mut(), workspace_id, doc_id, title)
.await
.map_err(db_err)?;
}
if let Some(pd) = upsert_doc_properties_in(
tx.tx_mut(),
@@ -778,32 +924,9 @@ async fn lock_workspace_docs_ordered(
}
Ok(())
}
fn merge_snapshot_and_updates(snap: Option<Vec<u8>>, upds: Vec<Vec<u8>>) -> Result<Option<Vec<u8>>, DomainError> {
if snap.is_none() && upds.is_empty() {
return Ok(None);
}
let mut parts: Vec<Vec<u8>> = snap.into_iter().chain(upds).filter(|b| !b.is_empty()).collect();
match parts.len() {
0 => Ok(Some(Vec::new())),
1 => Ok(Some(parts.pop().unwrap_or_default())),
_ => Ok(Some(
y_octo::merge_updates_v1(&parts)
.and_then(|u| u.encode_v1())
.map_err(y_err)?,
)),
}
}
async fn load_and_merge_doc_exec(
conn: &mut sqlx::PgConnection,
ws: &str,
doc: &str,
) -> Result<Option<Vec<u8>>, DomainError> {
let sq = sqlx::query_scalar("SELECT blob FROM snapshots WHERE workspace_id = $1 AND guid = $2");
let snapshot: Option<Vec<u8>> = sq.bind(ws).bind(doc).fetch_optional(&mut *conn).await.map_err(db_err)?;
let uq = sqlx::query_scalar("SELECT blob FROM updates WHERE workspace_id = $1 AND guid = $2 ORDER BY created_at ASC");
let updates: Vec<Vec<u8>> = uq.bind(ws).bind(doc).fetch_all(&mut *conn).await.map_err(db_err)?;
merge_snapshot_and_updates(snapshot, updates)
}
const MAX_MCP_DOC_BYTES: usize = 32 * 1024 * 1024;
const MAX_MCP_SYSTEM_DOC_BYTES: usize = 64 * 1024 * 1024;
async fn append_doc_update_in(
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
ws: &str,
@@ -828,14 +951,41 @@ async fn open_system_doc_in(
workspace_id: &str,
doc_id: &str,
) -> Result<(bool, y_octo::Doc, Option<Vec<u8>>), DomainError> {
let existing = load_and_merge_doc_exec(tx, workspace_id, doc_id).await?;
let existed = existing.is_some();
let (doc, sv) = match existing {
Some(ref b) if !b.is_empty() => (
y_octo::Doc::try_from_binary_v1(b).map_err(y_err)?,
Some(y_octo::encode_state_vector_from_update_v1(b).map_err(y_err)?),
),
_ => (y_octo::Doc::new(), None),
let parts = match crate::doc_sharing::DocSharingService::load_doc_parts_bounded_in(
tx,
workspace_id,
doc_id,
MAX_MCP_SYSTEM_DOC_BYTES,
)
.await
{
Ok(parts) => parts,
Err(ref err) if crate::doc_sharing::is_doc_parts_too_large(err) => {
return Err(DomainError::Validation(
"Workspace system document exceeds the 64 MiB size limit.".to_owned(),
));
}
Err(err) => return Err(err),
};
let existed = parts.is_some();
let (doc, sv) = match parts {
Some(parts) => tokio::task::spawn_blocking(move || {
let Some(merged) = crate::yjs_read::merge_update_parts_bounded(parts, MAX_MCP_SYSTEM_DOC_BYTES).map_err(y_err)?
else {
return Err(DomainError::Validation(
"Workspace system document exceeds the 64 MiB size limit.".to_owned(),
));
};
if merged.is_empty() {
return Ok((y_octo::Doc::new(), None));
}
let doc = y_octo::Doc::try_from_binary_v1(&merged).map_err(y_err)?;
let sv = y_octo::encode_state_vector_from_update_v1(&merged).map_err(y_err)?;
Ok((doc, Some(sv)))
})
.await
.map_err(int_err("join open system doc"))??,
None => (y_octo::Doc::new(), None),
};
Ok((existed, doc, sv))
}
@@ -992,18 +1142,6 @@ async fn upsert_doc_properties_in(
}
finish_system_doc_in(tx, ws, props_id, existed, &doc, before_sv.as_deref(), actor).await
}
async fn upsert_workspace_page_in(
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
ws: &str,
doc_id: &str,
title: &str,
) -> Result<(), DomainError> {
sqlx::query(
"INSERT INTO workspace_pages (workspace_id, page_id, mode, blocked, title) VALUES ($1, $2, 0, false, $3) ON CONFLICT (workspace_id, page_id) DO UPDATE SET title = EXCLUDED.title",
)
.bind(ws).bind(doc_id).bind(title).execute(&mut **tx).await.map_err(db_err)?;
Ok(())
}
fn row_to_view(row: sqlx::postgres::PgRow, now: DateTime<Utc>) -> McpCredentialView {
let access_mode_str: String = row.get("access_mode");
let expires_at: DateTime<Utc> = row.get("expires_at");
@@ -1697,22 +1835,129 @@ fn mutate_doc_body_delta(merged_existing: &[u8], body_markdown: &str) -> Result<
let full_after = doc.encode_update_v1().map_err(int_err("encode doc after body"))?;
diff_yjs_v1(&full_after, &before_sv, "diff doc body")
}
fn extract_title_from_blocks(blocks: &y_octo::Map, page_id: &str) -> Option<String> {
let y_octo::Value::Map(page) = blocks.get(page_id)? else {
return None;
fn read_map_str(map: y_octo::ReadMap<'_>, key: &str) -> Option<String> {
map
.get(key)
.and_then(y_octo::ReadValue::as_any)
.and_then(|a| a.as_str())
.map(str::to_owned)
}
fn read_map_bool(map: y_octo::ReadMap<'_>, key: &str) -> bool {
map
.get(key)
.and_then(y_octo::ReadValue::as_any)
.and_then(|a| a.as_bool())
== Some(true)
}
fn read_ytext_str(map: y_octo::ReadMap<'_>, key: &str) -> String {
match map.get(key) {
Some(y_octo::ReadValue::Text(t)) => t.to_string(),
_ => String::new(),
}
}
fn read_array_child_ids(map: y_octo::ReadMap<'_>) -> Vec<String> {
let Some(arr) = map.get("sys:children").and_then(y_octo::ReadValue::as_array) else {
return Vec::new();
};
let y_octo::Value::Text(t) = page.get("prop:title")? else {
arr
.iter()
.filter_map(|v| v.as_any().and_then(|a| a.as_str()).map(str::to_owned))
.collect()
}
fn find_single_page_id_read(blocks: y_octo::ReadMap<'_>) -> Option<String> {
let mut pages = Vec::new();
for (k, v) in blocks.iter() {
if let Some(m) = v.as_map()
&& read_map_str(m, "sys:flavour").as_deref() == Some("affine:page")
{
pages.push(k.to_owned());
}
}
if pages.len() != 1 {
return None;
}
Some(pages.remove(0))
}
fn find_primary_note_id_read(blocks: y_octo::ReadMap<'_>, page_id: &str) -> Option<String> {
let page = blocks.get(page_id).and_then(y_octo::ReadValue::as_map)?;
let mut first_note = None;
for cid in read_array_child_ids(page) {
if let Some(m) = blocks.get(&cid).and_then(y_octo::ReadValue::as_map)
&& read_map_str(m, "sys:flavour").as_deref() == Some("affine:note")
{
if first_note.is_none() {
first_note = Some(cid.clone());
}
if read_map_str(m, "prop:displayMode").as_deref() != Some("edgeless") {
return Some(cid);
}
}
}
first_note
}
fn reversible_image_source_read(blocks: y_octo::ReadMap<'_>, block_id: &str) -> Option<String> {
let m = blocks.get(block_id).and_then(y_octo::ReadValue::as_map)?;
(read_map_str(m, "sys:flavour").as_deref() == Some("affine:image") && read_array_child_ids(m).is_empty())
.then(|| read_map_str(m, "prop:sourceId").filter(|s| !s.is_empty()))
.flatten()
}
fn is_editable_subtree_read_inner(
blocks: y_octo::ReadMap<'_>,
block_id: &str,
depth: usize,
visited: &mut HashSet<String>,
require_list: bool,
) -> bool {
if depth > 32 || !visited.insert(block_id.to_owned()) {
return false;
}
let Some(m) = blocks.get(block_id).and_then(y_octo::ReadValue::as_map) else {
return false;
};
let flavour = read_map_str(m, "sys:flavour");
if require_list && flavour.as_deref() != Some("affine:list") {
return false;
}
let cids = read_array_child_ids(m);
let text = read_ytext_str(m, "prop:text");
match flavour.as_deref() {
Some("affine:paragraph") => {
let ptype = read_map_str(m, "prop:type").unwrap_or_else(|| "text".to_owned());
cids.is_empty()
&& matches!(
ptype.as_str(),
"text" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "quote"
)
&& !text.is_empty()
&& !text.contains("\n\n")
&& (ptype == "text" || !text.contains('\n'))
}
Some("affine:list") => {
matches!(
read_map_str(m, "prop:type").as_deref().unwrap_or("bulleted"),
"bulleted" | "numbered" | "todo"
) && !text.contains('\n')
&& cids
.iter()
.all(|cid| is_editable_subtree_read_inner(blocks, cid, depth + 1, visited, true))
}
Some("affine:code") => cids.is_empty() && !text.lines().any(|l| l.trim().starts_with("```")),
Some("affine:divider") => cids.is_empty(),
_ => false,
}
}
fn is_editable_subtree_read(blocks: y_octo::ReadMap<'_>, block_id: &str) -> bool {
is_editable_subtree_read_inner(blocks, block_id, 0, &mut HashSet::new(), false)
}
fn extract_title_from_read_blocks(blocks: y_octo::ReadMap<'_>, page_id: &str) -> Option<String> {
let page = blocks.get(page_id).and_then(y_octo::ReadValue::as_map)?;
let y_octo::ReadValue::Text(t) = page.get("prop:title")? else {
return None;
};
Some(t.to_string())
}
fn extract_title_from_yjs(blob: &[u8]) -> Option<String> {
let doc = y_octo::Doc::try_from_binary_v1(blob).ok()?;
let blocks = doc.get_or_create_map("blocks").ok()?;
extract_title_from_blocks(&blocks, &find_single_page_id(&blocks).ok()?)
}
fn render_list_lines(
blocks: &y_octo::Map,
fn render_list_lines_read(
blocks: y_octo::ReadMap<'_>,
block_id: &str,
list_depth: usize,
depth: usize,
@@ -1722,41 +1967,46 @@ fn render_list_lines(
if depth > 64 || !visited.insert(block_id.to_owned()) {
return;
}
let Some(y_octo::Value::Map(m)) = blocks.get(block_id) else {
let Some(m) = blocks.get(block_id).and_then(y_octo::ReadValue::as_map) else {
return;
};
if map_str(&m, "sys:flavour").as_deref() != Some("affine:list") {
if read_map_str(m, "sys:flavour").as_deref() != Some("affine:list") {
return;
}
let prefix = match map_str(&m, "prop:type").as_deref() {
let prefix = match read_map_str(m, "prop:type").as_deref() {
Some("numbered") => "1. ",
Some("todo") if map_bool(&m, "prop:checked") => "- [x] ",
Some("todo") if read_map_bool(m, "prop:checked") => "- [x] ",
Some("todo") => "- [ ] ",
_ => "- ",
};
lines.push(format!(
"{}{prefix}{}",
" ".repeat(list_depth),
ytext_str(&m, "prop:text")
read_ytext_str(m, "prop:text")
));
for cid in array_child_ids(&m) {
render_list_lines(blocks, &cid, list_depth + 1, depth + 1, visited, lines);
for cid in read_array_child_ids(m) {
render_list_lines_read(blocks, &cid, list_depth + 1, depth + 1, visited, lines);
}
}
fn render_block_tree(blocks: &y_octo::Map, block_id: &str, visited: &mut HashSet<String>, out: &mut Vec<String>) {
let Some(y_octo::Value::Map(m)) = blocks.get(block_id) else {
fn render_block_tree_read(
blocks: y_octo::ReadMap<'_>,
block_id: &str,
visited: &mut HashSet<String>,
out: &mut Vec<String>,
) {
let Some(m) = blocks.get(block_id).and_then(y_octo::ReadValue::as_map) else {
return;
};
match map_str(&m, "sys:flavour").as_deref() {
match read_map_str(m, "sys:flavour").as_deref() {
Some("affine:list") => {
let mut lines = Vec::new();
render_list_lines(blocks, block_id, 0, 0, visited, &mut lines);
render_list_lines_read(blocks, block_id, 0, 0, visited, &mut lines);
if !lines.is_empty() {
out.push(lines.join("\n"));
}
}
Some("affine:paragraph") if visited.insert(block_id.to_owned()) => {
let prefix = match map_str(&m, "prop:type").as_deref() {
let prefix = match read_map_str(m, "prop:type").as_deref() {
Some("h1") => "# ",
Some("h2") => "## ",
Some("h3") => "### ",
@@ -1766,7 +2016,7 @@ fn render_block_tree(blocks: &y_octo::Map, block_id: &str, visited: &mut HashSet
Some("quote") => "> ",
_ => "",
};
let text = ytext_str(&m, "prop:text");
let text = read_ytext_str(m, "prop:text");
let line = if prefix.is_empty() {
text
.split('\n')
@@ -1789,41 +2039,42 @@ fn render_block_tree(blocks: &y_octo::Map, block_id: &str, visited: &mut HashSet
}
Some("affine:code") if visited.insert(block_id.to_owned()) => out.push(format!(
"```{}\n{}\n```",
map_str(&m, "prop:language").unwrap_or_default(),
ytext_str(&m, "prop:text")
read_map_str(m, "prop:language").unwrap_or_default(),
read_ytext_str(m, "prop:text")
)),
Some("affine:divider") if visited.insert(block_id.to_owned()) => out.push("---".to_owned()),
Some("affine:image") if visited.insert(block_id.to_owned()) => {
if let Some(src) = map_str(&m, "prop:sourceId") {
out.push(format!("![{}]({src})", map_str(&m, "prop:caption").unwrap_or_default()));
if let Some(src) = read_map_str(m, "prop:sourceId") {
out.push(format!(
"![{}]({src})",
read_map_str(m, "prop:caption").unwrap_or_default()
));
}
}
_ => {}
}
}
fn extract_title_and_markdown_from_yjs(blob: &[u8]) -> (Option<String>, String) {
let Some(doc) = y_octo::Doc::try_from_binary_v1(blob).ok() else {
let Ok(doc) = crate::yjs_read::load_yjs_doc(Arc::<[u8]>::from(blob)) else {
return (None, String::new());
};
let Ok(blocks) = doc.get_or_create_map("blocks") else {
let Some(blocks) = doc.map("blocks") else {
return (None, String::new());
};
let Ok(page_id) = find_single_page_id(&blocks) else {
let Some(page_id) = find_single_page_id_read(blocks) else {
return (None, String::new());
};
let title_opt = extract_title_from_blocks(&blocks, &page_id);
let body = find_primary_note_id(&blocks, &page_id)
.and_then(|nid| match blocks.get(&nid)? {
y_octo::Value::Map(note) => {
let (mut parts, mut visited) = (Vec::new(), HashSet::new());
for cid in array_child_ids(&note) {
if is_editable_subtree(&blocks, &cid) || reversible_image_source(&blocks, &cid).is_some() {
render_block_tree(&blocks, &cid, &mut visited, &mut parts);
}
let title_opt = extract_title_from_read_blocks(blocks, &page_id);
let body = find_primary_note_id_read(blocks, &page_id)
.and_then(|nid| {
let note = blocks.get(&nid).and_then(y_octo::ReadValue::as_map)?;
let (mut parts, mut visited) = (Vec::new(), HashSet::new());
for cid in read_array_child_ids(note) {
if is_editable_subtree_read(blocks, &cid) || reversible_image_source_read(blocks, &cid).is_some() {
render_block_tree_read(blocks, &cid, &mut visited, &mut parts);
}
Some(parts.join("\n\n"))
}
_ => None,
Some(parts.join("\n\n"))
})
.unwrap_or_default();
let title = title_opt.as_deref().unwrap_or("");
@@ -1835,3 +2086,239 @@ fn extract_title_and_markdown_from_yjs(blob: &[u8]) -> (Option<String>, String)
};
(title_opt, md)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn read_map_and_mutable_map_block_predicates_match_1_to_1() {
use y_octo::{Any, Doc};
let doc = Doc::with_client(901);
let mut blocks = doc.get_or_create_map("blocks").unwrap();
let add_children = |doc: &Doc, m: &mut y_octo::Map, ids: &[&str]| {
let mut arr = doc.create_array().unwrap();
for id in ids {
arr.push(Any::String((*id).into())).unwrap();
}
m.insert("sys:children".to_owned(), arr).unwrap();
};
let add_text = |doc: &Doc, m: &mut y_octo::Map, key: &str, val: &str| {
let mut t = doc.create_text().unwrap();
if !val.is_empty() {
t.insert(0, val).unwrap();
}
m.insert(key.to_owned(), t).unwrap();
};
// Page + two notes (first edgeless, second primary page note).
let mut page = doc.create_map().unwrap();
page
.insert("sys:flavour".to_owned(), Any::String("affine:page".into()))
.unwrap();
add_text(&doc, &mut page, "prop:title", "Parity Page");
add_children(&doc, &mut page, &["note-edgeless", "note-primary"]);
blocks.insert("page-1".to_owned(), page).unwrap();
let mut note_edgeless = doc.create_map().unwrap();
note_edgeless
.insert("sys:flavour".to_owned(), Any::String("affine:note".into()))
.unwrap();
note_edgeless
.insert("prop:displayMode".to_owned(), Any::String("edgeless".into()))
.unwrap();
add_children(&doc, &mut note_edgeless, &[]);
blocks.insert("note-edgeless".to_owned(), note_edgeless).unwrap();
let all_block_ids = [
"p-text",
"p-h1",
"p-h2",
"p-h3",
"p-h4",
"p-h5",
"p-h6",
"p-quote",
"p-double-nl",
"p-heading-nl",
"list-bullet",
"list-num",
"list-todo",
"code-ok",
"code-fence",
"divider-ok",
"img-rev",
"img-children",
"img-child-para",
"unknown-block",
];
let mut note_primary = doc.create_map().unwrap();
note_primary
.insert("sys:flavour".to_owned(), Any::String("affine:note".into()))
.unwrap();
note_primary
.insert("prop:displayMode".to_owned(), Any::String("both".into()))
.unwrap();
add_children(&doc, &mut note_primary, &all_block_ids);
blocks.insert("note-primary".to_owned(), note_primary).unwrap();
// Paragraphs: text, h1..h6, quote, double newline (non-editable), heading with newline (non-editable).
for (id, ptype, body) in [
("p-text", "text", "plain paragraph\nwith single break"),
("p-h1", "h1", "Heading 1"),
("p-h2", "h2", "Heading 2"),
("p-h3", "h3", "Heading 3"),
("p-h4", "h4", "Heading 4"),
("p-h5", "h5", "Heading 5"),
("p-h6", "h6", "Heading 6"),
("p-quote", "quote", "Quoted line"),
("p-double-nl", "text", "para one\n\npara two"),
("p-heading-nl", "h2", "Heading\nwith break"),
] {
let mut p = doc.create_map().unwrap();
p.insert("sys:flavour".to_owned(), Any::String("affine:paragraph".into()))
.unwrap();
p.insert("prop:type".to_owned(), Any::String(ptype.into())).unwrap();
add_text(&doc, &mut p, "prop:text", body);
add_children(&doc, &mut p, &[]);
blocks.insert(id.to_owned(), p).unwrap();
}
// Nested lists: bulleted -> numbered -> todo.
let mut l_todo = doc.create_map().unwrap();
l_todo
.insert("sys:flavour".to_owned(), Any::String("affine:list".into()))
.unwrap();
l_todo
.insert("prop:type".to_owned(), Any::String("todo".into()))
.unwrap();
l_todo.insert("prop:checked".to_owned(), Any::True).unwrap();
add_text(&doc, &mut l_todo, "prop:text", "todo leaf");
add_children(&doc, &mut l_todo, &[]);
blocks.insert("list-todo".to_owned(), l_todo).unwrap();
let mut l_num = doc.create_map().unwrap();
l_num
.insert("sys:flavour".to_owned(), Any::String("affine:list".into()))
.unwrap();
l_num
.insert("prop:type".to_owned(), Any::String("numbered".into()))
.unwrap();
add_text(&doc, &mut l_num, "prop:text", "numbered mid");
add_children(&doc, &mut l_num, &["list-todo"]);
blocks.insert("list-num".to_owned(), l_num).unwrap();
let mut l_bullet = doc.create_map().unwrap();
l_bullet
.insert("sys:flavour".to_owned(), Any::String("affine:list".into()))
.unwrap();
l_bullet
.insert("prop:type".to_owned(), Any::String("bulleted".into()))
.unwrap();
add_text(&doc, &mut l_bullet, "prop:text", "bullet root");
add_children(&doc, &mut l_bullet, &["list-num"]);
blocks.insert("list-bullet".to_owned(), l_bullet).unwrap();
// Code blocks: editable vs containing backtick fence.
for (id, body) in [("code-ok", "fn main() {}"), ("code-fence", "let x = 1;\n```rust\n")] {
let mut c = doc.create_map().unwrap();
c.insert("sys:flavour".to_owned(), Any::String("affine:code".into()))
.unwrap();
add_text(&doc, &mut c, "prop:text", body);
add_children(&doc, &mut c, &[]);
blocks.insert(id.to_owned(), c).unwrap();
}
// Divider.
let mut div = doc.create_map().unwrap();
div
.insert("sys:flavour".to_owned(), Any::String("affine:divider".into()))
.unwrap();
add_children(&doc, &mut div, &[]);
blocks.insert("divider-ok".to_owned(), div).unwrap();
// Images: reversible (no children) vs non-reversible (with child).
let mut img_rev = doc.create_map().unwrap();
img_rev
.insert("sys:flavour".to_owned(), Any::String("affine:image".into()))
.unwrap();
img_rev
.insert("prop:sourceId".to_owned(), Any::String("blob-rev-1".into()))
.unwrap();
add_children(&doc, &mut img_rev, &[]);
blocks.insert("img-rev".to_owned(), img_rev).unwrap();
let mut img_child_para = doc.create_map().unwrap();
img_child_para
.insert("sys:flavour".to_owned(), Any::String("affine:paragraph".into()))
.unwrap();
add_text(&doc, &mut img_child_para, "prop:text", "nested");
add_children(&doc, &mut img_child_para, &[]);
blocks.insert("img-child-para".to_owned(), img_child_para).unwrap();
let mut img_children = doc.create_map().unwrap();
img_children
.insert("sys:flavour".to_owned(), Any::String("affine:image".into()))
.unwrap();
img_children
.insert("prop:sourceId".to_owned(), Any::String("blob-nonrev".into()))
.unwrap();
add_children(&doc, &mut img_children, &["img-child-para"]);
blocks.insert("img-children".to_owned(), img_children).unwrap();
// Unknown flavour block.
let mut unk = doc.create_map().unwrap();
unk
.insert("sys:flavour".to_owned(), Any::String("affine:database".into()))
.unwrap();
add_children(&doc, &mut unk, &[]);
blocks.insert("unknown-block".to_owned(), unk).unwrap();
let bin = doc.encode_update_v1().unwrap();
let read_doc = crate::yjs_read::load_yjs_doc(Arc::<[u8]>::from(bin)).expect("decode ReadDoc");
let read_blocks = read_doc.map("blocks").expect("blocks ReadMap");
assert_eq!(find_single_page_id_read(read_blocks), find_single_page_id(&blocks).ok());
let page_id = find_single_page_id_read(read_blocks).expect("single page");
assert_eq!(
find_primary_note_id_read(read_blocks, &page_id),
find_primary_note_id(&blocks, &page_id)
);
assert_eq!(
find_primary_note_id_read(read_blocks, &page_id).as_deref(),
Some("note-primary")
);
for block_id in all_block_ids {
assert_eq!(
is_editable_subtree_read(read_blocks, block_id),
is_editable_subtree(&blocks, block_id),
"is_editable_subtree mismatch for {block_id}"
);
assert_eq!(
reversible_image_source_read(read_blocks, block_id),
reversible_image_source(&blocks, block_id),
"reversible_image_source mismatch for {block_id}"
);
}
// Spot-check key expected truths so both sides can't silently agree on wrong values.
assert!(is_editable_subtree_read(read_blocks, "p-text"));
assert!(is_editable_subtree_read(read_blocks, "p-h6"));
assert!(!is_editable_subtree_read(read_blocks, "p-double-nl"));
assert!(!is_editable_subtree_read(read_blocks, "p-heading-nl"));
assert!(is_editable_subtree_read(read_blocks, "list-bullet"));
assert!(is_editable_subtree_read(read_blocks, "code-ok"));
assert!(!is_editable_subtree_read(read_blocks, "code-fence"));
assert!(is_editable_subtree_read(read_blocks, "divider-ok"));
assert!(!is_editable_subtree_read(read_blocks, "unknown-block"));
assert_eq!(
reversible_image_source_read(read_blocks, "img-rev").as_deref(),
Some("blob-rev-1")
);
assert_eq!(reversible_image_source_read(read_blocks, "img-children"), None);
}
}
@@ -463,57 +463,6 @@ impl NotificationService {
}
}
async fn load_workspace_display_name_in_tx(
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
workspace_id: &str,
) -> Result<String, DomainError> {
let db_name: Option<String> = sqlx::query_scalar("SELECT NULLIF(trim(name), '') FROM workspaces WHERE id = $1")
.bind(workspace_id)
.fetch_optional(&mut **tx)
.await
.map_err(|e| DomainError::Internal(format!("load invitation mail workspace name: {e}")))?
.flatten();
if let Some(name) = db_name {
return Ok(name);
}
let mut parts: Vec<Vec<u8>> = Vec::new();
if let Some(snap) =
sqlx::query_scalar::<_, Vec<u8>>("SELECT blob FROM snapshots WHERE workspace_id = $1 AND guid = $1")
.bind(workspace_id)
.fetch_optional(&mut **tx)
.await
.map_err(|e| DomainError::Internal(format!("load workspace root snapshot for name: {e}")))?
&& !snap.is_empty()
{
parts.push(snap);
}
let updates: Vec<Vec<u8>> =
sqlx::query_scalar("SELECT blob FROM updates WHERE workspace_id = $1 AND guid = $1 ORDER BY created_at ASC")
.bind(workspace_id)
.fetch_all(&mut **tx)
.await
.map_err(|e| DomainError::Internal(format!("load workspace root updates for name: {e}")))?;
parts.extend(updates.into_iter().filter(|b| !b.is_empty()));
if !parts.is_empty() {
let merged = if parts.len() == 1 {
Some(parts.remove(0))
} else {
y_octo::merge_updates_v1(&parts).and_then(|u| u.encode_v1()).ok()
};
if let Some(bin) = merged
&& let Ok(doc) = y_octo::Doc::try_from_binary_v1(&bin)
&& let Ok(meta) = doc.get_or_create_map("meta")
&& let Some(y_octo::Value::Any(y_octo::Any::String(raw))) = meta.get("name")
{
let trimmed = raw.trim();
if !trimmed.is_empty() {
return Ok(trimmed.to_owned());
}
}
}
Ok("Untitled Workspace".to_owned())
}
pub fn compute_recipient_hash(private_key: &str, email: &str) -> String {
use hmac::{Hmac, Mac as _};
use sha2::{Digest as _, Sha256};
@@ -736,7 +685,7 @@ pub async fn insert_invitation_notification_with_key_in_tx(
_ => return Ok(notif_id),
};
let workspace_name = load_workspace_display_name_in_tx(tx, workspace_id).await?;
let workspace_name = crate::workspaces::load_workspace_display_name_for_mail(tx, workspace_id).await?;
let props = if has_user {
let actor_email: String = sqlx::query_scalar("SELECT email FROM users WHERE id = $1")
.bind(created_by_user_id)
+188 -104
View File
@@ -322,7 +322,8 @@ impl WorkspaceService {
init_bytes: Option<&[u8]>,
) -> Result<WorkspaceRecord, DomainError> {
if let Some(bytes) = init_bytes {
validate_workspace_init_update(bytes)?;
let owned = bytes.to_vec();
crate::yjs_read::run_with_doc_decode_permit(move || validate_workspace_init_update(&owned)).await?;
}
let mut tx = self
@@ -3149,6 +3150,10 @@ impl WorkspaceService {
.begin_tiered(WorkloadTier::InteractiveRead)
.await
.map_err(|e| DomainError::Internal(format!("begin get_invite_info details: {e}")))?;
sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
.execute(&mut **tx.tx_mut())
.await
.map_err(|e| DomainError::Internal(format!("set repeatable read for get_invite_info: {e}")))?;
let ws_row = sqlx::query("SELECT name, avatar_key FROM workspaces WHERE id = $1")
.bind(&workspace_id)
.fetch_optional(&mut **tx.tx_mut())
@@ -3164,16 +3169,43 @@ impl WorkspaceService {
.map(|s| s.trim().to_owned())
.filter(|s| !s.is_empty());
let (yjs_name, yjs_avatar) = load_workspace_root_meta_in_tx(tx.tx_mut(), &workspace_id).await?;
let invitee = crate::users::load_current_user_in_tx(tx.tx_mut(), &invitee_user_id)
.await?
.ok_or_else(|| DomainError::NotFound("user not found".to_owned()))?;
let root_parts = match crate::doc_sharing::DocSharingService::load_doc_parts_bounded_in(
tx.tx_mut(),
&workspace_id,
&workspace_id,
crate::doc_sharing::MAX_PUBLIC_ROOT_DOC_BYTES,
)
.await
{
Ok(parts) => parts,
Err(ref err) if crate::doc_sharing::is_doc_parts_too_large(err) => {
tracing::warn!(
workspace_id = %workspace_id,
"skipping oversized workspace root metadata read for invite info"
);
None
}
Err(e) => return Err(e),
};
let _ = tx.rollback().await;
let (yjs_name, yjs_avatar) = if let Some(parts) = root_parts {
let ws_id_for_meta = workspace_id.clone();
crate::yjs_read::run_with_doc_decode_permit(move || {
let merged = crate::yjs_read::merge_update_parts(parts).ok();
Ok(extract_trimmed_workspace_root_meta(&ws_id_for_meta, merged.as_deref()))
})
.await?
} else {
(None, None)
};
let workspace_name = yjs_name
.or(db_workspace_name)
.unwrap_or_else(|| "Untitled Workspace".to_owned());
let workspace_avatar_key = yjs_avatar.or(db_avatar_key);
let invitee = crate::users::load_current_user_in_tx(tx.tx_mut(), &invitee_user_id)
.await?
.ok_or_else(|| DomainError::NotFound("user not found".to_owned()))?;
let _ = tx.rollback().await;
let owner = self.get_workspace_owner(&workspace_id).await?;
Ok(InviteInfoView {
@@ -3228,7 +3260,7 @@ pub struct DeletedWorkspaceCleanup {
pub comment_attachments: Vec<(String, String)>,
}
async fn load_workspace_display_name_for_mail(
pub(crate) async fn load_workspace_display_name_for_mail(
tx: &mut Transaction<'_, Postgres>,
workspace_id: &str,
) -> Result<String, DomainError> {
@@ -3241,7 +3273,40 @@ async fn load_workspace_display_name_for_mail(
if let Some(name) = db_name {
return Ok(name);
}
let (yjs_name, _) = load_workspace_root_meta_in_tx(tx, workspace_id).await?;
let root_parts = match crate::doc_sharing::DocSharingService::load_doc_parts_bounded_in(
tx,
workspace_id,
workspace_id,
crate::doc_sharing::MAX_PUBLIC_ROOT_DOC_BYTES,
)
.await
{
Ok(parts) => parts,
Err(ref err) if crate::doc_sharing::is_doc_parts_too_large(err) => {
tracing::warn!(
workspace_id = %workspace_id,
"skipping oversized workspace root display name read"
);
return Ok("Untitled Workspace".to_owned());
}
Err(e) => return Err(e),
};
let Some(parts) = root_parts else {
return Ok("Untitled Workspace".to_owned());
};
let ws_id = workspace_id.to_owned();
let decoded = crate::yjs_read::try_run_with_doc_decode_permit(move || {
let merged = crate::yjs_read::merge_update_parts(parts).ok();
Ok(extract_trimmed_workspace_root_meta(&ws_id, merged.as_deref()))
})
.await?;
let Some((yjs_name, _)) = decoded else {
tracing::warn!(
workspace_id = %workspace_id,
"skipping workspace display name decode because decode permits are busy"
);
return Ok("Untitled Workspace".to_owned());
};
Ok(yjs_name.unwrap_or_else(|| "Untitled Workspace".to_owned()))
}
@@ -3253,59 +3318,53 @@ pub async fn load_workspace_root_meta_from_pool(
pool: &sqlx::PgPool,
workspace_id: &str,
) -> Result<Option<(Option<String>, Option<String>)>, DomainError> {
let mut tx = pool
.begin()
.await
.map_err(|e| DomainError::Internal(format!("begin load_workspace_root_meta_from_pool: {e}")))?;
sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
.execute(&mut *tx)
.await
.map_err(|e| DomainError::Internal(format!("set repeatable read for workspace meta from pool: {e}")))?;
let ws_row = sqlx::query("SELECT name, avatar_key FROM workspaces WHERE id = $1")
.bind(workspace_id)
.fetch_optional(pool)
.fetch_optional(&mut *tx)
.await
.map_err(|e| DomainError::Internal(format!("load workspace meta from pool: {e}")))?;
let mut parts: Vec<Vec<u8>> = Vec::new();
if let Some(snap) =
sqlx::query_scalar::<_, Vec<u8>>("SELECT blob FROM snapshots WHERE workspace_id = $1 AND guid = $1")
.bind(workspace_id)
.fetch_optional(pool)
.await
.map_err(|e| DomainError::Internal(format!("load workspace root snapshot from pool: {e}")))?
&& !snap.is_empty()
let root_parts = match crate::doc_sharing::DocSharingService::load_doc_parts_bounded_in(
&mut tx,
workspace_id,
workspace_id,
crate::doc_sharing::MAX_PUBLIC_ROOT_DOC_BYTES,
)
.await
{
parts.push(snap);
}
let updates: Vec<Vec<u8>> =
sqlx::query_scalar("SELECT blob FROM updates WHERE workspace_id = $1 AND guid = $1 ORDER BY created_at ASC")
.bind(workspace_id)
.fetch_all(pool)
.await
.map_err(|e| DomainError::Internal(format!("load workspace root updates from pool: {e}")))?;
parts.extend(updates.into_iter().filter(|b| !b.is_empty()));
Ok(parts) => parts,
Err(ref err) if crate::doc_sharing::is_doc_parts_too_large(err) => {
tracing::warn!(
workspace_id = %workspace_id,
"skipping oversized workspace root metadata read from pool"
);
None
}
Err(e) => return Err(e),
};
let _ = tx.rollback().await;
if ws_row.is_none() && parts.is_empty() {
if ws_row.is_none() && root_parts.is_none() {
return Ok(None);
}
let (yjs_name, yjs_avatar) = if parts.is_empty() {
(None, None)
let (yjs_name, yjs_avatar) = if let Some(parts) = root_parts {
let ws_id = workspace_id.to_owned();
crate::yjs_read::run_with_doc_decode_permit(move || {
let merged = crate::yjs_read::merge_update_parts(parts).ok();
Ok(extract_trimmed_workspace_root_meta(&ws_id, merged.as_deref()))
})
.await?
} else {
let merged = if parts.len() == 1 {
Some(parts.remove(0))
} else {
y_octo::merge_updates_v1(&parts).and_then(|u| u.encode_v1()).ok()
};
merged
.and_then(|bin| y_octo::Doc::try_from_binary_v1(&bin).ok())
.and_then(|doc| doc.get_or_create_map("meta").ok())
.map(|meta| {
let extract = |key: &str| -> Option<String> {
match meta.get(key) {
Some(y_octo::Value::Any(y_octo::Any::String(raw))) => {
let trimmed = raw.trim();
(!trimmed.is_empty()).then(|| trimmed.to_owned())
}
_ => None,
}
};
(extract("name"), extract("avatar"))
})
.unwrap_or((None, None))
(None, None)
};
let db_name = ws_row
@@ -3322,59 +3381,31 @@ pub async fn load_workspace_root_meta_from_pool(
Ok(Some((yjs_name.or(db_name), yjs_avatar.or(db_avatar))))
}
async fn load_workspace_root_meta_in_tx(
tx: &mut Transaction<'_, Postgres>,
workspace_id: &str,
) -> Result<(Option<String>, Option<String>), DomainError> {
let mut parts: Vec<Vec<u8>> = Vec::new();
if let Some(snap) =
sqlx::query_scalar::<_, Vec<u8>>("SELECT blob FROM snapshots WHERE workspace_id = $1 AND guid = $1")
.bind(workspace_id)
.fetch_optional(&mut **tx)
.await
.map_err(|e| DomainError::Internal(format!("load workspace root snapshot for meta: {e}")))?
&& !snap.is_empty()
{
parts.push(snap);
}
let updates: Vec<Vec<u8>> =
sqlx::query_scalar("SELECT blob FROM updates WHERE workspace_id = $1 AND guid = $1 ORDER BY created_at ASC")
.bind(workspace_id)
.fetch_all(&mut **tx)
.await
.map_err(|e| DomainError::Internal(format!("load workspace root updates for meta: {e}")))?;
parts.extend(updates.into_iter().filter(|b| !b.is_empty()));
if parts.is_empty() {
return Ok((None, None));
}
let merged = if parts.len() == 1 {
Some(parts.remove(0))
} else {
y_octo::merge_updates_v1(&parts).and_then(|u| u.encode_v1()).ok()
fn extract_trimmed_workspace_root_meta(workspace_id: &str, bin: Option<&[u8]>) -> (Option<String>, Option<String>) {
let Some(bin) = bin else {
return (None, None);
};
let Some(bin) = merged else {
return Ok((None, None));
};
let Ok(doc) = y_octo::Doc::try_from_binary_v1(&bin) else {
return Ok((None, None));
};
let Ok(meta) = doc.get_or_create_map("meta") else {
return Ok((None, None));
};
let extract_str = |key: &str| -> Option<String> {
match meta.get(key) {
Some(y_octo::Value::Any(y_octo::Any::String(raw))) => {
let trimmed = raw.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed.to_owned())
}
}
_ => None,
match crate::doc_meta::parse_workspace_doc_content(bin) {
Ok(Some(meta)) => {
let trim = |value: Option<String>| {
value.and_then(|raw| {
let trimmed = raw.trim();
(!trimmed.is_empty()).then(|| trimmed.to_owned())
})
};
(trim(meta.name), trim(meta.avatar_key))
}
};
Ok((extract_str("name"), extract_str("avatar")))
Ok(None) => (None, None),
Err(err) => {
tracing::warn!(
workspace_id = %workspace_id,
doc_id = %workspace_id,
error = %err,
"skipping workspace root metadata read due to decode error"
);
(None, None)
}
}
}
/// Computes effective storage usage (in bytes) for `workspace_id` under `grant`.
@@ -3710,7 +3741,7 @@ fn validate_workspace_init_update(bytes: &[u8]) -> Result<(), DomainError> {
if bytes.len() > MAX_INIT_BYTES {
return Err(DomainError::Validation("workspace init document is too large".into()));
}
y_octo::ReadDoc::from_full_update_v1(bytes.to_vec())
y_octo::ReadDoc::from_full_update_v1(Arc::<[u8]>::from(bytes))
.map_err(|err| DomainError::Validation(format!("invalid Yjs document update: {err}")))?;
let mut sink = RejectZeroLengthSink::default();
@@ -3815,7 +3846,7 @@ mod tests {
}
#[test]
fn validate_workspace_init_update_rejects_zero_length_struct_frames() {
fn validate_workspace_init_update_rejects_zero_length_and_incomplete_updates() {
let doc = y_octo::Doc::with_client(1);
let mut meta = doc.get_or_create_map("meta").unwrap();
meta
@@ -3851,5 +3882,58 @@ mod tests {
"expected step-2 write-boundary zero-length struct rejection, got: {err:?}"
);
}
// Step 3: Workspace init strictly rejects incomplete snapshots (missing base delta).
let base_doc = y_octo::Doc::with_client(2);
let mut base_meta = base_doc.get_or_create_map("meta").unwrap();
base_meta
.insert("name".to_owned(), y_octo::Any::String("base".into()))
.unwrap();
let sv = base_doc.get_state_vector();
base_meta
.insert("avatar".to_owned(), y_octo::Any::String("av".into()))
.unwrap();
let incomplete_delta = base_doc.encode_state_as_update_v1(&sv).unwrap();
assert!(matches!(
y_octo::ReadDoc::from_full_update_v1(incomplete_delta.clone()),
Err(y_octo::ReadError::IncompleteSnapshot(_))
));
let incomplete_err = validate_workspace_init_update(&incomplete_delta).unwrap_err();
assert!(
matches!(incomplete_err, DomainError::Validation(_)),
"workspace init must reject incomplete snapshots, got: {incomplete_err:?}"
);
// Step 4: Same-client `[Item, Skip]` trailing Skip update: tolerant ReadDoc::from_update_v1
// succeeds with `!is_incomplete()`, while strict validate_workspace_init_update (from_full_update_v1)
// rejects it as IncompleteSnapshot.
let mut trailing_skip = Vec::new();
push_varuint(&mut trailing_skip, 1); // 1 client
push_varuint(&mut trailing_skip, 2); // 2 structs: Item + trailing Skip
push_varuint(&mut trailing_skip, 900_003); // client id
push_varuint(&mut trailing_skip, 0); // start clock 0
trailing_skip.push(0x04); // Content::String, no origin/right_origin, has parent
trailing_skip.push(0x01); // named root parent
push_varstring(&mut trailing_skip, "text");
push_varstring(&mut trailing_skip, "a");
trailing_skip.push(10); // Skip struct tag
push_varuint(&mut trailing_skip, 1); // skip length 1
push_varuint(&mut trailing_skip, 0); // empty delete set
let tolerant = y_octo::ReadDoc::from_update_v1(trailing_skip.clone())
.expect("tolerant ReadDoc::from_update_v1 must accept trailing Skip");
assert!(
!tolerant.is_incomplete(),
"trailing Skip alone leaves no pending structs"
);
assert!(matches!(
y_octo::ReadDoc::from_full_update_v1(trailing_skip.clone()),
Err(y_octo::ReadError::IncompleteSnapshot(_))
));
let trailing_skip_err = validate_workspace_init_update(&trailing_skip).unwrap_err();
assert!(
matches!(trailing_skip_err, DomainError::Validation(_)),
"workspace init must reject trailing Skip update, got: {trailing_skip_err:?}"
);
}
}
@@ -0,0 +1,298 @@
//! Shared bounded `y-octo` reader built directly on [`y_octo::ReadDoc`].
//!
//! Every production reader decodes through [`load_yjs_doc`] or
//! [`load_yjs_doc_with_limits`], delegating full and incomplete v1 updates
//! directly to `y_octo::ReadDoc::from_update_v1[_with_limits]` under bounded
//! `ReadLimits` without falling back to an unbounded `Doc`.
use std::sync::{Arc, OnceLock};
use server_types::DomainError;
use tokio::sync::Semaphore;
/// Shared concurrency gate for CPU-bound Yjs document decoding on request paths.
pub fn doc_decode_semaphore() -> &'static Arc<Semaphore> {
static SEM: OnceLock<Arc<Semaphore>> = OnceLock::new();
SEM.get_or_init(|| {
let permits = std::thread::available_parallelism().map_or(4, usize::from).clamp(2, 8);
Arc::new(Semaphore::new(permits))
})
}
/// Runs a blocking Yjs decode closure on `tokio::task::spawn_blocking` while
/// holding an owned permit from `semaphore`.
pub async fn run_with_decode_semaphore<T, F>(semaphore: &Arc<Semaphore>, f: F) -> Result<T, DomainError>
where
T: Send + 'static,
F: FnOnce() -> Result<T, DomainError> + Send + 'static,
{
let permit = Arc::clone(semaphore)
.acquire_owned()
.await
.map_err(|_| DomainError::Unavailable("doc decode semaphore closed".to_owned()))?;
tokio::task::spawn_blocking(move || {
let _permit = permit;
f()
})
.await
.map_err(|err| DomainError::Internal(format!("join doc decode task: {err}")))?
}
/// Non-blocking admission variant of [`run_with_decode_semaphore`] for paths
/// inside an active transaction. Uses `try_acquire_owned` so callers
/// immediately see `Ok(None)` when all permits are busy and never queue on the
/// semaphore; once a permit is acquired immediately, the closure still runs on
/// `tokio::task::spawn_blocking` while the caller awaits its result.
pub async fn try_run_with_decode_semaphore<T, F>(semaphore: &Arc<Semaphore>, f: F) -> Result<Option<T>, DomainError>
where
T: Send + 'static,
F: FnOnce() -> Result<T, DomainError> + Send + 'static,
{
let Ok(permit) = Arc::clone(semaphore).try_acquire_owned() else {
return Ok(None);
};
let out = tokio::task::spawn_blocking(move || {
let _permit = permit;
f()
})
.await
.map_err(|err| DomainError::Internal(format!("join doc decode task: {err}")))??;
Ok(Some(out))
}
/// Runs a blocking Yjs decode closure on `tokio::task::spawn_blocking` while
/// holding an owned permit from [`doc_decode_semaphore`].
pub async fn run_with_doc_decode_permit<T, F>(f: F) -> Result<T, DomainError>
where
T: Send + 'static,
F: FnOnce() -> Result<T, DomainError> + Send + 'static,
{
run_with_decode_semaphore(doc_decode_semaphore(), f).await
}
/// Non-blocking admission variant of [`run_with_doc_decode_permit`].
pub async fn try_run_with_doc_decode_permit<T, F>(f: F) -> Result<Option<T>, DomainError>
where
T: Send + 'static,
F: FnOnce() -> Result<T, DomainError> + Send + 'static,
{
try_run_with_decode_semaphore(doc_decode_semaphore(), f).await
}
/// Merges Yjs v1 update parts into a single v1 update binary.
pub fn merge_update_parts(mut parts: Vec<Vec<u8>>) -> Result<Vec<u8>, y_octo::JwstCodecError> {
match parts.len() {
0 => Ok(Vec::new()),
1 => Ok(parts.pop().unwrap_or_default()),
_ => y_octo::merge_updates_v1(parts).and_then(|u| u.encode_v1()),
}
}
/// Merges Yjs v1 update parts and returns `Ok(None)` if either the total input
/// byte size or the merged binary exceeds `max_bytes`.
pub fn merge_update_parts_bounded(
parts: Vec<Vec<u8>>,
max_bytes: usize,
) -> Result<Option<Vec<u8>>, y_octo::JwstCodecError> {
let total_input = parts
.iter()
.try_fold(0usize, |acc, part| acc.checked_add(part.len()))
.unwrap_or(usize::MAX);
if total_input > max_bytes {
return Ok(None);
}
let merged = merge_update_parts(parts)?;
if merged.len() > max_bytes {
return Ok(None);
}
Ok(Some(merged))
}
/// Decodes `bytes` under [`y_octo::ReadLimits::default()`].
pub fn load_yjs_doc(bytes: Arc<[u8]>) -> Result<y_octo::ReadDoc, y_octo::ReadError> {
y_octo::ReadDoc::from_update_v1(bytes)
}
/// Decodes `bytes` under explicit `limits`, enforcing `ResourceLimit` and
/// `InvalidUpdate` strictly while handling incomplete updates inside `y-octo`.
pub fn load_yjs_doc_with_limits(
bytes: Arc<[u8]>,
limits: y_octo::ReadLimits,
) -> Result<y_octo::ReadDoc, y_octo::ReadError> {
y_octo::ReadDoc::from_update_v1_with_limits(bytes, limits)
}
#[cfg(test)]
mod tests {
use y_octo::{AHashMap, Any, DocOptions, ReadDoc, ReadError, ReadLimits, ReadTextRun, TextAttributes};
use super::*;
fn make_client_gap_update(client_id: u64) -> Vec<u8> {
let doc = DocOptions::new().with_client_id(client_id).build();
let mut map = doc.get_or_create_map("gap").unwrap();
map.insert("a".to_owned(), Any::String("1".into())).unwrap();
let sv = doc.get_state_vector();
map.insert("b".to_owned(), Any::String("2".into())).unwrap();
doc.encode_state_as_update_v1(&sv).unwrap()
}
#[test]
fn load_yjs_doc_reads_incomplete_snapshot_without_cloning_large_text_attributes() {
// Reproduces the large-format-attribute + incomplete-snapshot adversarial shape:
// client 1 inserts 1,000 chars, applies a 100 KB `reference` attribute across [0, 1000),
// and toggles `b: true` on every even position (500 intervals -> 1,000 format items).
let doc1 = DocOptions::new().with_client_id(1).build();
let mut text = doc1.get_or_create_text("body").unwrap();
let body = "x".repeat(1_000);
text.insert(0, &body).unwrap();
let large_ref_obj: AHashMap<String, Any> = [
("pageId".to_owned(), Any::String("target-page-1".into())),
("pad".to_owned(), Any::String("p".repeat(100 * 1024))),
]
.into_iter()
.collect();
let mut ref_attrs = TextAttributes::new();
ref_attrs.insert("reference".to_owned(), Any::Object(Box::new(large_ref_obj)));
text.format(0, 1_000, ref_attrs).unwrap();
for i in (0..1_000u64).step_by(2) {
let mut bold = TextAttributes::new();
bold.insert("b".to_owned(), Any::True);
text.format(i, 1, bold).unwrap();
}
let c1_update = doc1.encode_update_v1().unwrap();
let c2_gap = make_client_gap_update(2);
let combined = y_octo::merge_updates_v1([c1_update, c2_gap])
.and_then(|u| u.encode_v1())
.unwrap();
assert!(matches!(
ReadDoc::from_full_update_v1(combined.clone()),
Err(ReadError::IncompleteSnapshot(_))
));
let read_doc = load_yjs_doc(Arc::<[u8]>::from(combined)).expect("decode incomplete snapshot as ReadDoc");
assert!(read_doc.is_incomplete());
let read_text = read_doc.text("body").expect("body text");
assert_eq!(read_text.len(), 1_000);
let mut text_len = 0usize;
let mut format_events = 0usize;
let mut saw_ref_page_id = false;
for run in read_text.runs() {
match run {
ReadTextRun::Text(s) => text_len += s.len(),
ReadTextRun::Format { key, value } => {
format_events += 1;
if key == "reference" && value.get("pageId").and_then(|v| v.as_str()) == Some("target-page-1") {
saw_ref_page_id = true;
}
}
ReadTextRun::Embed(_) => {}
}
}
assert_eq!(text_len, 1_000);
// 2 events for `reference` (open + close) + 1,000 events for 500 `b` intervals (open + close).
assert_eq!(format_events, 1_002);
assert!(saw_ref_page_id);
}
#[test]
fn load_yjs_doc_reads_ready_prefix_with_missing_dependency_and_clips_delete_set() {
// Client 1 creates a root map with an integrated key; client 2 creates a nested map
// (missing from the final update); client 3 writes into client 2's nested map so client 3
// has a missing cross-client parent dependency.
let doc1 = DocOptions::new().with_client_id(1).build();
let mut keep = doc1.get_or_create_map("keep").unwrap();
keep.insert("a".to_owned(), Any::String("alive".into())).unwrap();
keep.insert("b".to_owned(), Any::String("gone".into())).unwrap();
let c1_full = doc1.encode_update_v1().unwrap();
// Delete key "b" on client 1, then also create an unintegrated client 2 + dependent client 3.
let mut doc1_del = DocOptions::new().with_client_id(1).build();
doc1_del.apply_update_from_binary_v1(&c1_full).unwrap();
let mut keep_del = doc1_del.get_or_create_map("keep").unwrap();
keep_del.remove("b");
let c1_with_del = doc1_del.encode_update_v1().unwrap();
let doc2 = DocOptions::new().with_client_id(2).build();
let mut root2 = doc2.get_or_create_map("dep_root").unwrap();
let nested = doc2.create_map().unwrap();
root2.insert("child".to_owned(), nested).unwrap();
let sv2 = doc2.get_state_vector();
let mut doc3 = DocOptions::new().with_client_id(3).build();
doc3
.apply_update_from_binary_v1(doc2.encode_update_v1().unwrap())
.unwrap();
let Some(y_octo::Value::Map(mut child_on_3)) = doc3.get_map("dep_root").unwrap().get("child") else {
panic!("expected child map on client 3");
};
child_on_3.insert("k".to_owned(), Any::String("orphan".into())).unwrap();
// Encode only client 3's update (omits client 2's parent item), plus a delete on client 2.
let c3_missing_parent = doc3.encode_state_as_update_v1(&sv2).unwrap();
// Also include a client 4 with a gap and a DeleteSet targeting client 4's unintegrated range.
let doc4 = DocOptions::new().with_client_id(4).build();
let mut m4 = doc4.get_or_create_map("m4").unwrap();
m4.insert("k1".to_owned(), Any::String("v1".into())).unwrap();
let sv4 = doc4.get_state_vector();
m4.insert("k2".to_owned(), Any::String("v2".into())).unwrap();
m4.remove("k2");
let c4_gap_with_ds = doc4.encode_state_as_update_v1(&sv4).unwrap();
let combined = y_octo::merge_updates_v1([c1_with_del, c3_missing_parent, c4_gap_with_ds])
.and_then(|u| u.encode_v1())
.unwrap();
assert!(matches!(
ReadDoc::from_full_update_v1(combined.clone()),
Err(ReadError::IncompleteSnapshot(_))
));
let read_doc = load_yjs_doc(Arc::<[u8]>::from(combined)).expect("missing deps and delete set must decode cleanly");
assert!(read_doc.is_incomplete());
let read_keep = read_doc.map("keep").expect("keep map");
assert_eq!(
read_keep.get("a").and_then(|v| v.as_any()).and_then(|a| a.as_str()),
Some("alive")
);
assert!(read_keep.get("b").is_none(), "deleted key b must stay deleted");
assert!(read_doc.map("dep_root").is_none());
assert!(read_doc.map("m4").is_none());
}
#[test]
fn load_yjs_doc_enforces_phase2_virtual_struct_splits_limit_on_incomplete_update() {
// Keep the 40-char string as a single wire struct (`c1_insert`) and attach 20 disjoint
// single-char delete ranges in the DeleteSet (`c1_deletes`) so Phase-1 scan sees <= 2 wire
// structs (passing `max_structs: 16`) while Phase-2 resolve hits the virtual struct split cap.
let doc1 = DocOptions::new().with_client_id(1).build();
let mut text = doc1.get_or_create_text("t").unwrap();
text.insert(0, "a".repeat(40)).unwrap();
let c1_insert = doc1.encode_update_v1().unwrap();
let sv_after_insert = doc1.get_state_vector();
for i in (0..40usize).step_by(2).rev() {
text.remove(i as u64, 1).unwrap();
}
let c1_deletes = doc1.encode_state_as_update_v1(&sv_after_insert).unwrap();
let c2_gap = make_client_gap_update(2);
let combined = y_octo::merge_updates_v1([c1_insert, c1_deletes, c2_gap])
.and_then(|u| u.encode_v1())
.unwrap();
let small_limits = ReadLimits {
max_structs: 16,
..ReadLimits::default()
};
let err = load_yjs_doc_with_limits(Arc::<[u8]>::from(combined), small_limits)
.expect_err("Phase-2 virtual struct splits must still be enforced on incomplete update");
assert!(
matches!(err, ReadError::ResourceLimit("virtual struct splits")),
"expected ResourceLimit(\"virtual struct splits\"), got: {err:?}"
);
}
}
@@ -1003,3 +1003,427 @@ fn mcp_cyclic_and_deep_block_graphs_never_overflow_2mb_stack() {
.expect("spawn 2mb stack thread");
handle.join().expect("2mb stack thread must not overflow");
}
fn build_simple_page_snapshot(client_id: u64, title: &str, paragraph: &str) -> Vec<u8> {
let doc = y_octo::DocOptions::new().with_client_id(client_id).build();
let mut blocks = doc.get_or_create_map("blocks").unwrap();
let mut page = doc.create_map().unwrap();
page
.insert("sys:id".to_owned(), y_octo::Any::String("page:0".into()))
.unwrap();
page
.insert("sys:flavour".to_owned(), y_octo::Any::String("affine:page".into()))
.unwrap();
let mut title_text = doc.create_text().unwrap();
title_text.insert(0, title).unwrap();
page.insert("prop:title".to_owned(), title_text).unwrap();
let mut page_children = doc.create_array().unwrap();
page_children.push(y_octo::Any::String("note:0".into())).unwrap();
page.insert("sys:children".to_owned(), page_children).unwrap();
blocks.insert("page:0".to_owned(), page).unwrap();
let mut note = doc.create_map().unwrap();
note
.insert("sys:id".to_owned(), y_octo::Any::String("note:0".into()))
.unwrap();
note
.insert("sys:flavour".to_owned(), y_octo::Any::String("affine:note".into()))
.unwrap();
let mut note_children = doc.create_array().unwrap();
note_children.push(y_octo::Any::String("para:0".into())).unwrap();
note.insert("sys:children".to_owned(), note_children).unwrap();
blocks.insert("note:0".to_owned(), note).unwrap();
let mut para = doc.create_map().unwrap();
para
.insert("sys:id".to_owned(), y_octo::Any::String("para:0".into()))
.unwrap();
para
.insert("sys:flavour".to_owned(), y_octo::Any::String("affine:paragraph".into()))
.unwrap();
para
.insert("prop:type".to_owned(), y_octo::Any::String("text".into()))
.unwrap();
let mut para_text = doc.create_text().unwrap();
para_text.insert(0, paragraph).unwrap();
para.insert("prop:text".to_owned(), para_text).unwrap();
para
.insert("sys:children".to_owned(), doc.create_array().unwrap())
.unwrap();
blocks.insert("para:0".to_owned(), para).unwrap();
doc.encode_update_v1().unwrap()
}
#[test]
fn read_document_markdown_recovers_multipart_incomplete_snapshot() {
let cluster = PgCluster::from_env_or_docker().expect("pg cluster");
let lease = lease_test_db(&cluster);
let db_url = lease.url().to_owned();
let rt = test_runtime();
rt.block_on(async {
let db = connect_test_db(&db_url, 4).await;
let user_id = insert_user(&db, "mcp-incomplete@example.com").await;
let ws = insert_workspace(&db, &user_id).await;
let svc = McpCredentialService::new(db.clone(), Arc::new(NoopEventPublisher::default()));
let base_snap = build_simple_page_snapshot(101, "Ready Snapshot Title", "Ready snapshot body");
// Client 102 writes clock 0 then clock 1; encode only clock 1 so merging with base_snap produces a client clock gap.
let gap_doc = y_octo::DocOptions::new().with_client_id(102).build();
let mut scratch = gap_doc.get_or_create_map("scratch").unwrap();
scratch
.insert("a".to_owned(), y_octo::Any::String("skipped".into()))
.unwrap();
let sv = gap_doc.get_state_vector();
scratch
.insert("b".to_owned(), y_octo::Any::String("gap-tail".into()))
.unwrap();
let gap_update = gap_doc.encode_state_as_update_v1(&sv).unwrap();
let merged_check = y_octo::merge_updates_v1([base_snap.clone(), gap_update.clone()])
.and_then(|u| u.encode_v1())
.unwrap();
assert!(matches!(
y_octo::ReadDoc::from_full_update_v1(merged_check),
Err(y_octo::ReadError::IncompleteSnapshot(_))
));
let doc_id = Uuid::new_v4().to_string();
sqlx::query(
"INSERT INTO snapshots (workspace_id, guid, blob, size, created_at, updated_at, created_by, updated_by)
VALUES ($1, $2, $3, octet_length($3), clock_timestamp(), clock_timestamp(), $4, $4)",
)
.bind(&ws)
.bind(&doc_id)
.bind(&base_snap)
.bind(&user_id)
.execute(db.pool())
.await
.expect("insert base snapshot");
sqlx::query(
"INSERT INTO updates (workspace_id, guid, blob, created_at, created_by)
VALUES ($1, $2, $3, clock_timestamp(), $4)",
)
.bind(&ws)
.bind(&doc_id)
.bind(&gap_update)
.bind(&user_id)
.execute(db.pool())
.await
.expect("insert gap update");
let md = svc
.read_document_markdown(&ws, &doc_id)
.await
.expect("read multipart incomplete doc")
.expect("markdown present");
assert_eq!(md, "# Ready Snapshot Title\n\nReady snapshot body");
db.pool().close().await;
});
}
#[test]
fn recover_document_aborts_without_writes_when_decode_permits_busy_and_preserves_snapshot_meta() {
let cluster = PgCluster::from_env_or_docker().expect("pg cluster");
let lease = lease_test_db(&cluster);
let db_url = lease.url().to_owned();
let rt = test_runtime();
rt.block_on(async {
let db = connect_test_db(&db_url, 4).await;
let user_id = insert_user(&db, "mcp-recover-busy@example.com").await;
let ws = insert_workspace(&db, &user_id).await;
let sem = Arc::new(tokio::sync::Semaphore::new(2));
let svc = McpCredentialService::new(db.clone(), Arc::new(NoopEventPublisher::default()))
.with_decode_semaphore(Arc::clone(&sem));
let doc_id = Uuid::new_v4().to_string();
let snap_blob = build_simple_page_snapshot(201, "Original Snapshot Title", "Original snapshot summary body");
sqlx::query(
"INSERT INTO snapshots (workspace_id, guid, blob, size, created_at, updated_at, created_by, updated_by)
VALUES ($1, $2, $3, octet_length($3), clock_timestamp(), clock_timestamp(), $4, $4)",
)
.bind(&ws)
.bind(&doc_id)
.bind(&snap_blob)
.bind(&user_id)
.execute(db.pool())
.await
.expect("insert target snapshot");
// Exhaust all injected decode permits so try_run_with_decode_semaphore returns None
// without interfering with the process-wide semaphore used by parallel tests.
let busy_guard = sem
.clone()
.acquire_many_owned(2)
.await
.expect("acquire all decode permits");
let err = svc
.create_document(&ws, "Caller Fallback Title", "Ignored Body", &user_id, Some(&doc_id))
.await
.expect_err("recover must abort with Unavailable when decode permits are busy");
assert!(
matches!(err, server_types::DomainError::Unavailable(_)),
"expected DomainError::Unavailable, got: {err:?}"
);
// Verify zero writes occurred while permits were exhausted.
let page_rows: i64 =
sqlx::query_scalar("SELECT COUNT(*)::bigint FROM workspace_pages WHERE workspace_id = $1 AND page_id = $2")
.bind(&ws)
.bind(&doc_id)
.fetch_one(db.pool())
.await
.unwrap();
assert_eq!(page_rows, 0, "workspace_pages must remain untouched on busy abort");
let root_snaps: i64 =
sqlx::query_scalar("SELECT COUNT(*)::bigint FROM snapshots WHERE workspace_id = $1 AND guid = $1")
.bind(&ws)
.fetch_one(db.pool())
.await
.unwrap();
let root_upds: i64 =
sqlx::query_scalar("SELECT COUNT(*)::bigint FROM updates WHERE workspace_id = $1 AND guid = $1")
.bind(&ws)
.fetch_one(db.pool())
.await
.unwrap();
assert_eq!(root_snaps, 0, "root snapshot must remain untouched on busy abort");
assert_eq!(root_upds, 0, "root updates must remain untouched on busy abort");
let target_snap: Vec<u8> = sqlx::query_scalar("SELECT blob FROM snapshots WHERE workspace_id = $1 AND guid = $2")
.bind(&ws)
.bind(&doc_id)
.fetch_one(db.pool())
.await
.unwrap();
let target_upds: i64 =
sqlx::query_scalar("SELECT COUNT(*)::bigint FROM updates WHERE workspace_id = $1 AND guid = $2")
.bind(&ws)
.bind(&doc_id)
.fetch_one(db.pool())
.await
.unwrap();
assert_eq!(target_snap, snap_blob, "target snapshot must remain untouched");
assert_eq!(target_upds, 0, "target updates must remain untouched");
// Release permits and retry recovery with the same caller fallback title.
drop(busy_guard);
let recovered_id = svc
.create_document(&ws, "Caller Fallback Title", "Ignored Body", &user_id, Some(&doc_id))
.await
.expect("recover must succeed once decode permits are free");
assert_eq!(recovered_id, doc_id);
let (stored_title, stored_summary): (Option<String>, Option<String>) =
sqlx::query_as("SELECT title, summary FROM workspace_pages WHERE workspace_id = $1 AND page_id = $2")
.bind(&ws)
.bind(&doc_id)
.fetch_one(db.pool())
.await
.expect("workspace_pages row after recover");
assert_eq!(stored_title.as_deref(), Some("Original Snapshot Title"));
assert_eq!(stored_summary.as_deref(), Some("Original snapshot summary body"));
let root_snap: Vec<u8> = sqlx::query_scalar("SELECT blob FROM snapshots WHERE workspace_id = $1 AND guid = $1")
.bind(&ws)
.fetch_one(db.pool())
.await
.expect("root doc snapshot after recover");
let root_read = y_octo::ReadDoc::from_update_v1(Arc::<[u8]>::from(root_snap)).expect("decode root doc");
let root_pages = root_read
.map("meta")
.and_then(|m| m.get("pages"))
.and_then(y_octo::ReadValue::as_array)
.expect("meta.pages array");
let mut found_root_title = None;
for entry in root_pages.iter() {
if let Some(page) = entry.as_map()
&& page.get("id").and_then(|v| v.as_any()).and_then(|a| a.as_str()) == Some(doc_id.as_str())
{
found_root_title = page
.get("title")
.and_then(|v| v.as_any())
.and_then(|a| a.as_str())
.map(str::to_owned);
}
}
assert_eq!(found_root_title.as_deref(), Some("Original Snapshot Title"));
db.pool().close().await;
});
}
#[test]
fn mcp_writes_succeed_when_lifecycle_active_and_doc_properties_exceeds_16_mib() {
let cluster = PgCluster::from_env_or_docker().expect("pg cluster");
let lease = lease_test_db(&cluster);
let db_url = lease.url().to_owned();
let rt = test_runtime();
rt.block_on(async {
let db = connect_test_db(&db_url, 4).await;
sqlx::raw_sql("DROP SCHEMA public CASCADE; CREATE SCHEMA public;")
.execute(db.pool())
.await
.expect("reset schema");
db.ensure_schema_ready().await.expect("ensure schema ready");
let user_id = insert_user(&db, "mcp-large-props@example.com").await;
let ws = insert_workspace(&db, &user_id).await;
let svc = McpCredentialService::new(db.clone(), Arc::new(NoopEventPublisher::default()));
// Activate workspace_doc_lifecycle globally.
sqlx::query(
"INSERT INTO storage_reconciliation_checkpoints (kind, scope, status, updated_at)
VALUES ('workspace_doc_lifecycle_activation', 'global', 'active', now())
ON CONFLICT (kind, scope) DO UPDATE SET status = 'active', updated_at = now()",
)
.execute(db.pool())
.await
.expect("activate workspace_doc_lifecycle");
// Seed a valid >16 MiB (~17 MiB) db$<ws>$docProperties snapshot.
let props_doc_id = format!("db${ws}$docProperties");
let props_doc = y_octo::Doc::with_client(301);
let mut existing = props_doc.get_or_create_map("existing-large-entry").unwrap();
existing
.insert("id".to_owned(), y_octo::Any::String("existing-large-entry".into()))
.unwrap();
existing
.insert("pad".to_owned(), y_octo::Any::String("x".repeat(17 * 1024 * 1024)))
.unwrap();
let props_bin = props_doc.encode_update_v1().unwrap();
assert!(
props_bin.len() > 16 * 1024 * 1024,
"docProperties snapshot must exceed 16 MiB, got {} bytes",
props_bin.len()
);
sqlx::query(
"INSERT INTO snapshots (workspace_id, guid, blob, size, created_at, updated_at, created_by, updated_by)
VALUES ($1, $2, $3, octet_length($3), clock_timestamp(), clock_timestamp(), $4, $4)",
)
.bind(&ws)
.bind(&props_doc_id)
.bind(&props_bin)
.bind(&user_id)
.execute(db.pool())
.await
.expect("insert >16 MiB docProperties snapshot");
// 1. Create a small ordinary document.
let created_id = svc
.create_document(&ws, "Small Page", "Initial body", &user_id, None)
.await
.expect("create_document must succeed with >16 MiB docProperties");
// 2. Update its body and title.
let updated_body = svc
.update_document(&ws, &created_id, "Updated body content", &user_id)
.await
.expect("update_document must succeed with >16 MiB docProperties");
assert!(updated_body);
let updated_title = svc
.update_document_title(&ws, &created_id, "Updated Small Page", &user_id)
.await
.expect("update_document_title must succeed with >16 MiB docProperties");
assert!(updated_title);
// 3. Recover an existing snapshot into the same workspace.
let recover_id = Uuid::new_v4().to_string();
let recover_blob = build_simple_page_snapshot(302, "Recovered Page", "Recovered body");
sqlx::query(
"INSERT INTO snapshots (workspace_id, guid, blob, size, created_at, updated_at, created_by, updated_by)
VALUES ($1, $2, $3, octet_length($3), clock_timestamp(), clock_timestamp(), $4, $4)",
)
.bind(&ws)
.bind(&recover_id)
.bind(&recover_blob)
.bind(&user_id)
.execute(db.pool())
.await
.expect("insert recover snapshot");
let recovered = svc
.create_document(&ws, "Fallback", "Ignored", &user_id, Some(&recover_id))
.await
.expect("recover create_document must succeed with >16 MiB docProperties");
assert_eq!(recovered, recover_id);
// Verify docProperties now contains both created_id and recover_id updates alongside the existing entry.
let upd_count: i64 =
sqlx::query_scalar("SELECT COUNT(*)::bigint FROM updates WHERE workspace_id = $1 AND guid = $2")
.bind(&ws)
.bind(&props_doc_id)
.fetch_one(db.pool())
.await
.unwrap();
assert!(
upd_count >= 2,
"expected docProperties updates for created and recovered docs"
);
db.pool().close().await;
});
}
#[test]
fn recover_document_rejects_corrupt_snapshot_without_overwriting_existing_page_meta() {
let cluster = PgCluster::from_env_or_docker().expect("pg cluster");
let lease = lease_test_db(&cluster);
let db_url = lease.url().to_owned();
let rt = test_runtime();
rt.block_on(async {
let db = connect_test_db(&db_url, 4).await;
let user_id = insert_user(&db, "mcp-recover-corrupt@example.com").await;
let ws = insert_workspace(&db, &user_id).await;
let svc = McpCredentialService::new(db.clone(), Arc::new(NoopEventPublisher::default()));
let doc_id = Uuid::new_v4().to_string();
sqlx::query(
"INSERT INTO workspace_pages (workspace_id, page_id, title, summary)
VALUES ($1, $2, 'Existing Good Title', 'Existing Good Summary')",
)
.bind(&ws)
.bind(&doc_id)
.execute(db.pool())
.await
.expect("insert existing page metadata");
let corrupt_blob: Vec<u8> = vec![0xff, 0xff, 0xff];
sqlx::query(
"INSERT INTO snapshots (workspace_id, guid, blob, size, created_at, updated_at, created_by, updated_by)
VALUES ($1, $2, $3, octet_length($3), clock_timestamp(), clock_timestamp(), $4, $4)",
)
.bind(&ws)
.bind(&doc_id)
.bind(&corrupt_blob)
.bind(&user_id)
.execute(db.pool())
.await
.expect("insert corrupt snapshot");
let err = svc
.create_document(&ws, "Caller Wrong Title", "Body", &user_id, Some(&doc_id))
.await
.expect_err("corrupt snapshot recovery must fail with Validation error");
assert!(
matches!(err, server_types::DomainError::Validation(_)),
"expected DomainError::Validation, got: {err:?}"
);
let (title, summary): (Option<String>, Option<String>) =
sqlx::query_as("SELECT title, summary FROM workspace_pages WHERE workspace_id = $1 AND page_id = $2")
.bind(&ws)
.bind(&doc_id)
.fetch_one(db.pool())
.await
.expect("workspace_pages row must remain intact");
assert_eq!(title.as_deref(), Some("Existing Good Title"));
assert_eq!(summary.as_deref(), Some("Existing Good Summary"));
db.pool().close().await;
});
}
@@ -2,7 +2,7 @@
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::{Mutex, OnceLock};
use std::sync::{Arc, Mutex, OnceLock};
use axum::Router;
use axum::extract::{Path as AxumPath, State};
@@ -16,7 +16,7 @@ use server_types::DeploymentMode;
use sha2::{Digest as _, Sha256};
use sqlx::Row as _;
use v_htmlescape::escape as esc;
use y_octo::{Any, Doc, Value as YValue};
use y_octo::{ReadMap, ReadValue};
use crate::RouterState;
use crate::rest::resolve_request_principal_with_policy;
@@ -25,52 +25,60 @@ const STATIC_SUBPATHS: &[&str] = &["all", "home", "search", "collection", "tag",
const MARKDOWN_TYPES: &[&str] = &["text/markdown", "application/markdown", "text/x-markdown"];
const MAX_SUMMARY_CHARS: usize = 500;
const MAX_VIEW_DEDUPE_ENTRIES: usize = 16_384;
const MAX_RENDER_DOC_BYTES: usize = 16 * 1024 * 1024;
pub(crate) fn router() -> Router<RouterState> {
Router::new().route("/workspace/{*path}", get(handle_render_workspace_path))
}
type AssetsManifest = (Vec<String>, Vec<String>, String, String, String);
async fn load_merged_doc_snapshot(state: &RouterState, ws_id: &str, doc_id: &str) -> Option<Vec<u8>> {
let mut conn = state.app.db.acquire_tiered(WorkloadTier::InteractiveRead).await.ok()?;
let snap: Option<Vec<u8>> = sqlx::query_scalar("SELECT blob FROM snapshots WHERE workspace_id = $1 AND guid = $2")
.bind(ws_id)
.bind(doc_id)
.fetch_optional(conn.as_conn())
async fn load_and_render_doc_markdown(
state: &RouterState,
ws_id: &str,
doc_id: &str,
) -> Option<(String, String, String)> {
let mut tx = state.app.db.begin_tiered(WorkloadTier::InteractiveRead).await.ok()?;
sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
.execute(&mut **tx.tx_mut())
.await
.ok()
.flatten();
let updates: Vec<Vec<u8>> =
sqlx::query_scalar("SELECT blob FROM updates WHERE workspace_id = $1 AND guid = $2 ORDER BY created_at ASC")
.bind(ws_id)
.bind(doc_id)
.fetch_all(conn.as_conn())
.await
.unwrap_or_default();
drop(conn);
if snap.is_none() && updates.is_empty() {
return None;
}
let mut doc = Doc::default();
for bin in snap.into_iter().chain(updates) {
if !bin.is_empty() {
let _ = doc.apply_update_from_binary_v1(&bin);
}
}
doc.encode_state_as_update_v1(&y_octo::StateVector::default()).ok()
.ok()?;
let parts = server_domain::doc_sharing::DocSharingService::load_doc_parts_bounded_in(
tx.tx_mut(),
ws_id,
doc_id,
MAX_RENDER_DOC_BYTES,
)
.await
.ok()
.flatten();
let _ = tx.rollback().await;
let parts = parts?;
server_domain::yjs_read::run_with_doc_decode_permit(move || {
let Ok(Some(merged)) = server_domain::yjs_read::merge_update_parts_bounded(parts, MAX_RENDER_DOC_BYTES) else {
return Ok(None);
};
Ok(render_doc_markdown_from_binary(&merged))
})
.await
.ok()
.flatten()
}
fn y_str(m: &y_octo::Map, k: &str) -> String {
match m.get(k) {
Some(YValue::Any(Any::String(s))) => s,
_ => String::new(),
}
fn y_str(m: ReadMap<'_>, k: &str) -> String {
m.get(k)
.and_then(ReadValue::as_any)
.and_then(|a| a.as_str())
.map(str::to_owned)
.unwrap_or_default()
}
pub fn render_doc_markdown_from_binary(bin: &[u8]) -> Option<(String, String, String)> {
let mut doc = Doc::default();
doc.apply_update_from_binary_v1(bin).ok()?;
let blocks = doc.get_or_create_map("blocks").ok()?;
let doc = server_domain::yjs_read::load_yjs_doc(Arc::<[u8]>::from(bin)).ok()?;
let blocks = doc.map("blocks")?;
let (mut title, mut lines, mut visited) = (String::new(), Vec::new(), HashSet::new());
let mut roots: Vec<String> = blocks
.iter()
.filter_map(|(id, v)| matches!(v, YValue::Map(b) if y_str(&b, "sys:flavour") == "affine:page").then_some(id))
.filter_map(|(id, v)| {
v.as_map()
.filter(|&b| y_str(b, "sys:flavour") == "affine:page")
.map(|_| id.to_owned())
})
.collect();
roots.sort();
let mut stack: Vec<(String, usize, usize)> = roots.into_iter().rev().map(|id| (id, 0, 0)).collect();
@@ -78,25 +86,25 @@ pub fn render_doc_markdown_from_binary(bin: &[u8]) -> Option<(String, String, St
if depth > 64 || !visited.insert(id.clone()) {
continue;
}
let Some(YValue::Map(block)) = blocks.get(&id) else {
let Some(block) = blocks.get(&id).and_then(ReadValue::as_map) else {
continue;
};
let flavour = y_str(&block, "sys:flavour");
if flavour == "affine:surface" || (flavour == "affine:note" && y_str(&block, "prop:displayMode") == "edgeless") {
let flavour = y_str(block, "sys:flavour");
if flavour == "affine:surface" || (flavour == "affine:note" && y_str(block, "prop:displayMode") == "edgeless") {
continue;
}
if flavour == "affine:page" {
if let Some(YValue::Text(t)) = block.get("prop:title") {
if let Some(ReadValue::Text(t)) = block.get("prop:title") {
let s = t.to_string();
if !s.trim().is_empty() {
title = s.trim().to_owned();
}
}
} else if let Some(YValue::Text(t)) = block.get("prop:text") {
} else if let Some(ReadValue::Text(t)) = block.get("prop:text") {
let raw = t.to_string();
let trimmed = raw.trim();
if !trimmed.is_empty() {
let ptype = y_str(&block, "prop:type");
let ptype = y_str(block, "prop:type");
let ind = " ".repeat(list_depth);
let line = match (flavour.as_str(), ptype.as_str()) {
("affine:paragraph", h @ ("h1" | "h2" | "h3" | "h4" | "h5" | "h6")) => {
@@ -105,9 +113,15 @@ pub fn render_doc_markdown_from_binary(bin: &[u8]) -> Option<(String, String, St
("affine:paragraph", "quote") => format!("> {trimmed}"),
("affine:list", "numbered") => format!("{ind}1. {trimmed}"),
("affine:list", "todo") => {
let chk = match block.get("prop:checked") {
Some(YValue::Any(Any::True)) => "x",
_ => " ",
let chk = if block
.get("prop:checked")
.and_then(ReadValue::as_any)
.and_then(|a| a.as_bool())
== Some(true)
{
"x"
} else {
" "
};
format!("{ind}- [{chk}] {trimmed}")
}
@@ -119,15 +133,12 @@ pub fn render_doc_markdown_from_binary(bin: &[u8]) -> Option<(String, String, St
}
}
if depth < 64
&& let Some(YValue::Array(children)) = block.get("sys:children")
&& let Some(children) = block.get("sys:children").and_then(ReadValue::as_array)
{
let next_ld = list_depth + usize::from(flavour == "affine:list");
let cids: Vec<String> = children
.iter()
.filter_map(|c| match c {
YValue::Any(Any::String(s)) => Some(s),
_ => None,
})
.filter_map(|c| c.as_any().and_then(|a| a.as_str()).map(str::to_owned))
.collect();
for cid in cids.into_iter().rev() {
stack.push((cid, depth + 1, next_ld));
@@ -208,15 +219,12 @@ async fn handle_render_workspace_path(
let can_read = state
.app
.doc_sharing
.get_doc_permissions(ws_id, uid, doc_id)
.get_resolved_doc_permissions(ws_id, uid, doc_id)
.await
.ok()
.flatten()
.is_some_and(|p| p.doc_read);
let mut resp = if can_read
&& let Some(bin) = load_merged_doc_snapshot(&state, ws_id, doc_id).await
&& let Some((_, _, md)) = render_doc_markdown_from_binary(&bin)
{
let mut resp = if can_read && let Some((_, _, md)) = load_and_render_doc_markdown(&state, ws_id, doc_id).await {
(
StatusCode::OK,
[(header::CONTENT_TYPE, "text/markdown; charset=utf-8")],
@@ -238,13 +246,15 @@ async fn handle_render_workspace_path(
let ws_id = ws_opt.unwrap_or("");
if let Some(doc_id) = resolved_doc_id.as_deref() {
let raw_doc_id = sub_opt.unwrap_or("");
if let Ok(Some(perms)) = state.app.doc_sharing.get_doc_permissions(ws_id, None, doc_id).await
if let Ok(Some(perms)) = state
.app
.doc_sharing
.get_resolved_doc_permissions(ws_id, None, doc_id)
.await
&& perms.doc_preview
{
indexable = perms.doc_read;
if let Some(bin) = load_merged_doc_snapshot(&state, ws_id, doc_id).await
&& let Some((title, summary, _)) = render_doc_markdown_from_binary(&bin)
{
if let Some((title, summary, _)) = load_and_render_doc_markdown(&state, ws_id, doc_id).await {
meta = Some((title, summary, None));
}
if meta.is_some() {
@@ -1347,3 +1347,200 @@ fn rest_r2_proxy_upload_and_multipart_end_to_end() {
db.pool().close().await;
});
}
#[test]
fn doc_renderer_resolves_legacy_alias_once_per_request() {
let lease = leased_0275_database();
let db_url = lease.url().to_owned();
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()
.unwrap();
rt.block_on(async move {
let db = connect_db(&db_url).await;
let ws_id = "ws-alias-once";
sqlx::query("INSERT INTO workspaces (id, name) VALUES ($1, 'Alias Once WS')")
.bind(ws_id)
.execute(db.pool())
.await
.unwrap();
sqlx::query(
"INSERT INTO workspace_access_policies (workspace_id, visibility, sharing_enabled, url_preview_enabled)
VALUES ($1, 'public', true, true)
ON CONFLICT (workspace_id) DO UPDATE SET visibility = 'public', sharing_enabled = true, url_preview_enabled = true",
)
.bind(ws_id)
.execute(db.pool())
.await
.unwrap();
sqlx::query(
"INSERT INTO workspace_pages (workspace_id, page_id, published_at)
VALUES ($1, 'phys-doc-1', now())",
)
.bind(ws_id)
.execute(db.pool())
.await
.unwrap();
sqlx::query(
"INSERT INTO doc_access_policies (workspace_id, doc_id, visibility, public_role, published_at)
VALUES ($1, 'phys-doc-1', 'public', 'external', now())",
)
.bind(ws_id)
.execute(db.pool())
.await
.unwrap();
// Legacy workspace root doc mapping logical-doc-1 -> phys-doc-1 (lifecycle not active).
let root = Doc::with_client(601);
let mut meta = root.get_or_create_map("meta").unwrap();
let mut pages = root.create_array().unwrap();
let mut p = root.create_map().unwrap();
p.insert("id".to_owned(), Any::String("logical-doc-1".into())).unwrap();
pages.push(p).unwrap();
meta.insert("pages".to_owned(), pages).unwrap();
let mut spaces = root.get_or_create_map("spaces").unwrap();
let sub = Doc::with_options(y_octo::DocOptions::new().with_guid("phys-doc-1".to_owned()));
spaces.insert("logical-doc-1".to_owned(), sub).unwrap();
let root_bin = root.encode_update_v1().unwrap();
sqlx::query(
"INSERT INTO snapshots (workspace_id, guid, blob, size, created_at, updated_at)
VALUES ($1, $1, $2, $3, now(), now())",
)
.bind(ws_id)
.bind(&root_bin)
.bind(root_bin.len() as i64)
.execute(db.pool())
.await
.unwrap();
// Target physical page doc with title + paragraph.
let doc = Doc::with_client(602);
let mut blocks = doc.get_or_create_map("blocks").unwrap();
let mut page = doc.create_map().unwrap();
page
.insert("sys:flavour".to_owned(), Any::String("affine:page".into()))
.unwrap();
let mut title = doc.create_text().unwrap();
title.insert(0, "Aliased Render Title").unwrap();
page.insert("prop:title".to_owned(), title).unwrap();
let mut ch = doc.create_array().unwrap();
ch.push(Any::String("p1".into())).unwrap();
page.insert("sys:children".to_owned(), ch).unwrap();
blocks.insert("page".to_owned(), page).unwrap();
let mut para = doc.create_map().unwrap();
para
.insert("sys:flavour".to_owned(), Any::String("affine:paragraph".into()))
.unwrap();
let mut text = doc.create_text().unwrap();
text.insert(0, "Aliased render body").unwrap();
para.insert("prop:text".to_owned(), text).unwrap();
blocks.insert("p1".to_owned(), para).unwrap();
let doc_bin = doc.encode_update_v1().unwrap();
sqlx::query(
"INSERT INTO snapshots (workspace_id, guid, blob, size, created_at, updated_at)
VALUES ($1, 'phys-doc-1', $2, $3, now(), now())",
)
.bind(ws_id)
.bind(&doc_bin)
.bind(doc_bin.len() as i64)
.execute(db.pool())
.await
.unwrap();
let ext = Arc::new(CommunityExtension::new());
let state = AppState::new(
db.clone(),
None,
RuntimeConfig {
external_url: "http://affine.local".into(),
..RuntimeConfig::default()
},
ext,
);
let app = build_router(Arc::clone(&state));
struct AliasResolveSubscriber(Arc<std::sync::atomic::AtomicUsize>);
impl tracing::Subscriber for AliasResolveSubscriber {
fn enabled(&self, metadata: &tracing::Metadata<'_>) -> bool {
*metadata.level() <= tracing::Level::DEBUG
}
fn new_span(&self, _span: &tracing::span::Attributes<'_>) -> tracing::span::Id {
tracing::span::Id::from_u64(1)
}
fn record(&self, _span: &tracing::span::Id, _values: &tracing::span::Record<'_>) {}
fn record_follows_from(&self, _span: &tracing::span::Id, _follows: &tracing::span::Id) {}
fn event(&self, event: &tracing::Event<'_>) {
if event.metadata().target() == "affine::doc_sharing::alias" {
self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
}
fn enter(&self, _span: &tracing::span::Id) {}
fn exit(&self, _span: &tracing::span::Id) {}
}
use tracing::instrument::WithSubscriber as _;
// Markdown request: must resolve alias exactly once.
let md_count = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let md_resp = app
.clone()
.oneshot(
Request::builder()
.uri(format!("/workspace/{ws_id}/logical-doc-1"))
.header(header::ACCEPT, "text/markdown")
.body(Body::empty())
.unwrap(),
)
.with_subscriber(AliasResolveSubscriber(Arc::clone(&md_count)))
.await
.unwrap();
assert_eq!(md_resp.status(), StatusCode::OK);
let md_body = String::from_utf8(
axum::body::to_bytes(md_resp.into_body(), 16 * 1024)
.await
.unwrap()
.to_vec(),
)
.unwrap();
assert!(md_body.contains("Aliased Render Title"));
assert!(md_body.contains("Aliased render body"));
assert_eq!(
md_count.load(std::sync::atomic::Ordering::Relaxed),
1,
"markdown doc_renderer request must resolve legacy alias only once"
);
// HTML OG request: must also resolve alias exactly once.
let html_count = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let html_resp = app
.clone()
.oneshot(
Request::builder()
.uri(format!("/workspace/{ws_id}/logical-doc-1"))
.header(header::ACCEPT, "text/html")
.body(Body::empty())
.unwrap(),
)
.with_subscriber(AliasResolveSubscriber(Arc::clone(&html_count)))
.await
.unwrap();
assert_eq!(html_resp.status(), StatusCode::OK);
let html_body = String::from_utf8(
axum::body::to_bytes(html_resp.into_body(), 32 * 1024)
.await
.unwrap()
.to_vec(),
)
.unwrap();
assert!(html_body.contains("Aliased Render Title"));
assert_eq!(
html_count.load(std::sync::atomic::Ordering::Relaxed),
1,
"HTML doc_renderer request must resolve legacy alias only once"
);
db.pool().close().await;
});
}
+2 -1
View File
@@ -7,7 +7,8 @@
- Keep `SearchConfig::default().enabled` set to `false` to match `v0.27.5`.
- Do not depend on `napi` or `affine_doc_loader`.
- Extract document titles, text blocks, and canvas elements directly with `y-octo`.
- Take `search-projection-lifecycle` for generation creation and activation. Never take the legacy `search-projection-generation` global lock.
- Take `search-projection-generation` for generation creation and activation so `affine-server` serializes with `v0.27.5` under the `xid8` fence. Never take `search-projection-generation` in steady-state worker ticks or `search_projection_lockless_v2` lease renewals.
- When legacy write transactions hold the `search-projection-generation` shared lock, cold-path `ensure` and `activate` retry for up to `5s`. They return `IndexNotReady` without affecting active lease renewals.
- Take per-workspace `search-projection-ws:<workspace_id>` advisory locks for orphan GC high-water capture and document target enqueue.
Use a two-beat post-commit `fenceXid` discovery fence before latching `scan_high_water_sid`.
+170 -40
View File
@@ -1,12 +1,15 @@
mod reference;
use std::collections::{BTreeMap, BTreeSet, HashSet, VecDeque};
use std::sync::Arc;
use reference::{References, collect_cell_references, collect_text_references};
use serde::Serialize;
use serde_json::{Map as JsonMap, Value as JsonValue};
use server_domain::doc_sharing::is_empty_doc_bin;
use server_domain::yjs_read::load_yjs_doc;
use sha2::{Digest, Sha256};
use y_octo::{Any, Doc, ReadDoc, ReadMap, ReadValue, Value};
use y_octo::{ReadMap, ReadValue};
use crate::error::{SearchError, SearchResult};
@@ -90,7 +93,7 @@ pub fn project_document_search(blob: Vec<u8>, doc_id: String) -> SearchResult<Do
));
}
let source_hash = hex_sha256(&blob);
let doc = ReadDoc::from_full_update_v1(blob)
let doc = load_yjs_doc(Arc::<[u8]>::from(blob))
.map_err(|error| SearchError::SourceInvalid(format!("document decode failed: {error}")))?;
let mut title = String::new();
@@ -134,7 +137,7 @@ pub fn project_document_search(blob: Vec<u8>, doc_id: String) -> SearchResult<Do
}
while let Some((block_id, parent_block_id, parent_flavour)) = queue.pop_front() {
let Some(block) = blocks.get(&block_id).and_then(|value| value.as_map()) else {
let Some(block) = blocks.get(&block_id).and_then(ReadValue::as_map) else {
continue;
};
let flavour = read_text_field(block, "sys:flavour").unwrap_or_default();
@@ -219,7 +222,7 @@ pub fn project_document_search(blob: Vec<u8>, doc_id: String) -> SearchResult<Do
}
}
if let Some(children) = block.get("sys:children").and_then(|v| v.as_array()) {
if let Some(children) = block.get("sys:children").and_then(ReadValue::as_array) {
if children.len() > MAX_CHILDREN_PER_BLOCK {
return Err(SearchError::SourceInvalid(
"block child fanout exceeds limit".to_owned(),
@@ -245,16 +248,16 @@ pub fn project_document_search(blob: Vec<u8>, doc_id: String) -> SearchResult<Do
}
fn extract_surface_elements(block: ReadMap<'_>, block_id: &str, units: &mut Vec<SearchUnit>) {
let Some(elements) = block.get("prop:elements").and_then(|v| v.as_map()) else {
let Some(elements) = block.get("prop:elements").and_then(ReadValue::as_map) else {
return;
};
let mut keys: Vec<String> = elements.keys().map(str::to_owned).collect();
keys.sort();
let mut keys: Vec<&str> = elements.keys().collect();
keys.sort_unstable();
for key in keys {
let Some(elem) = elements.get(&key).and_then(|v| v.as_map()) else {
let Some(elem) = elements.get(key).and_then(ReadValue::as_map) else {
continue;
};
let elem_id = read_text_field(elem, "id").unwrap_or_else(|| key.clone());
let elem_id = read_text_field(elem, "id").unwrap_or_else(|| key.to_owned());
let elem_type = read_text_field(elem, "type").unwrap_or_else(|| "surface-element".to_owned());
let mut parts = Vec::new();
for field in ["title", "text", "label"] {
@@ -401,12 +404,20 @@ fn collect_database_column_texts(block: ReadMap<'_>, texts: &mut Vec<String>) {
/// Map values in key order. The decoded key order depends on the update
/// encoding, so sort to keep the extracted order stable.
fn sorted_values(map: ReadMap<'_>) -> Vec<ReadValue<'_>> {
let mut entries: Vec<_> = map.iter().collect();
fn sorted_values<'a>(map: ReadMap<'a>) -> Vec<ReadValue<'a>> {
let mut entries: Vec<(&str, ReadValue<'a>)> = map.iter().collect();
entries.sort_by_key(|(key, _)| *key);
entries.into_iter().map(|(_, value)| value).collect()
}
fn value_string(value: ReadValue<'_>) -> Option<String> {
match value {
ReadValue::Any(any) => any.as_str().map(str::to_owned),
ReadValue::Text(text) => Some(text.to_string()),
_ => None,
}
}
fn extract_block_additional(block: ReadMap<'_>, flavour: &str, database_name: Option<String>) -> Option<String> {
let mut obj = JsonMap::new();
if let Some(url) = read_text_field(block, "prop:url") {
@@ -427,14 +438,6 @@ fn extract_block_additional(block: ReadMap<'_>, flavour: &str, database_name: Op
}
}
fn value_string(value: ReadValue<'_>) -> Option<String> {
match value {
ReadValue::Text(text) => Some(text.to_string()),
ReadValue::Any(any) => any.as_str().map(str::to_owned),
_ => None,
}
}
/// The first non-blank of the common text properties.
fn block_text(block: ReadMap<'_>) -> Option<String> {
["prop:text", "prop:caption", "prop:latex", "prop:name"]
@@ -520,38 +523,52 @@ pub fn extract_legacy_workspace(
revision,
});
};
let mut doc = Doc::new();
doc
.apply_update_from_binary_v1(&blob)
if is_empty_doc_bin(&blob) {
return Ok(LegacyWorkspace {
documents: Vec::new(),
aliases: BTreeMap::new(),
revision,
});
}
if blob.len() > MAX_SOURCE_BINARY_BYTES {
return Err(SearchError::SourceInvalid(
"legacy workspace binary exceeds size limit".to_owned(),
));
}
let doc = load_yjs_doc(Arc::<[u8]>::from(blob))
.map_err(|error| SearchError::SourceInvalid(format!("legacy workspace root decode failed: {error}")))?;
let mut documents = Vec::new();
if doc.keys().iter().any(|k| k == "meta")
&& let Ok(meta) = doc.get_map("meta")
&& let Some(Value::Array(pages)) = meta.get("pages")
if let Some(meta) = doc.map("meta")
&& let Some(pages) = meta.get("pages").and_then(ReadValue::as_array)
{
for idx in 0..pages.len() {
if let Some(Value::Map(page)) = pages.get(idx) {
let id = match page.get("id") {
Some(Value::Any(Any::String(s))) => s,
_ => continue,
for entry in pages.iter() {
if let Some(page) = entry.as_map() {
let Some(id) = page
.get("id")
.and_then(ReadValue::as_any)
.and_then(|any| any.as_str())
.map(str::to_owned)
else {
continue;
};
let trash = matches!(page.get("trash"), Some(Value::Any(Any::True)));
let trash = page
.get("trash")
.and_then(ReadValue::as_any)
.and_then(|any| any.as_bool())
.unwrap_or(false);
documents.push(LegacyRootDocument { id, trash });
}
}
}
let mut aliases = BTreeMap::new();
if doc.keys().iter().any(|k| k == "spaces")
&& let Ok(spaces) = doc.get_map("spaces")
{
if let Some(spaces) = doc.map("spaces") {
for document in &documents {
if let Some(Value::Doc(subdoc)) = spaces.get(&document.id) {
let guid = subdoc.guid();
if crate::is_ordinary_workspace_doc(workspace_id, guid) {
aliases.insert(document.id.clone(), guid.to_owned());
}
if let Some(ReadValue::Doc { guid, .. }) = spaces.get(&document.id)
&& crate::is_ordinary_workspace_doc(workspace_id, guid)
{
aliases.insert(document.id.clone(), guid.to_owned());
}
}
}
@@ -571,7 +588,7 @@ mod test_doc;
mod tests {
use std::time::{Duration, Instant};
use y_octo::{TextAttributes, TextDeltaOp, TextInsert};
use y_octo::{Any, Doc, TextAttributes, TextDeltaOp, TextInsert, Value};
use super::test_doc::{TestDoc, TestValue, build_test_doc, object};
use super::*;
@@ -626,6 +643,119 @@ mod tests {
additional: Option<&'static str>,
}
#[test]
fn project_document_search_recovers_incomplete_snapshot_page_doc() {
let page_c1 = y_octo::DocOptions::new().with_client_id(701).build();
let mut blocks = page_c1.get_or_create_map("blocks").unwrap();
let mut page = page_c1.create_map().unwrap();
page
.insert("sys:id".to_owned(), Any::String("page-gap".into()))
.unwrap();
page
.insert("sys:flavour".to_owned(), Any::String("affine:page".into()))
.unwrap();
let mut title = page_c1.create_text().unwrap();
title.insert(0, "Gap Search Title").unwrap();
page.insert("prop:title".to_owned(), title).unwrap();
let mut children = page_c1.create_array().unwrap();
children.push(Any::String("para-gap".into())).unwrap();
page.insert("sys:children".to_owned(), children).unwrap();
blocks.insert("page-gap".to_owned(), page).unwrap();
let mut para = page_c1.create_map().unwrap();
para
.insert("sys:id".to_owned(), Any::String("para-gap".into()))
.unwrap();
para
.insert("sys:flavour".to_owned(), Any::String("affine:paragraph".into()))
.unwrap();
let mut text = page_c1.create_text().unwrap();
text.insert(0, "searchable gap body").unwrap();
para.insert("prop:text".to_owned(), text).unwrap();
blocks.insert("para-gap".to_owned(), para).unwrap();
let mut page_c2 = y_octo::DocOptions::new().with_client_id(702).build();
let mut scratch = page_c2.get_or_create_map("scratch").unwrap();
scratch.insert("a".to_owned(), Any::String("1".into())).unwrap();
let sv_c2 = page_c2.get_state_vector();
scratch.insert("b".to_owned(), Any::String("2".into())).unwrap();
page_c2
.apply_update_from_binary_v1(page_c1.encode_update_v1().unwrap())
.unwrap();
let delta_bin = page_c2.encode_state_as_update_v1(&sv_c2).unwrap();
assert!(matches!(
y_octo::ReadDoc::from_full_update_v1(delta_bin.clone()),
Err(y_octo::ReadError::IncompleteSnapshot(_))
));
let projection = project_document_search(delta_bin, "doc-gap".to_owned())
.expect("incomplete snapshot page doc must extract search units");
assert_eq!(projection.title, "Gap Search Title");
let para_unit = unit(&projection, "para-gap").expect("paragraph unit");
assert_eq!(para_unit.text, "searchable gap body");
// Large inline reference attribute + alternating format toggles + incomplete snapshot:
// verifies ReadDoc::from_update_v1 preserves inline references without to_delta cloning.
let adv_c1 = y_octo::DocOptions::new().with_client_id(711).build();
let mut adv_blocks = adv_c1.get_or_create_map("blocks").unwrap();
let mut adv_page = adv_c1.create_map().unwrap();
adv_page
.insert("sys:id".to_owned(), Any::String("page-adv".into()))
.unwrap();
adv_page
.insert("sys:flavour".to_owned(), Any::String("affine:page".into()))
.unwrap();
let mut adv_children = adv_c1.create_array().unwrap();
adv_children.push(Any::String("para-adv".into())).unwrap();
adv_page.insert("sys:children".to_owned(), adv_children).unwrap();
adv_blocks.insert("page-adv".to_owned(), adv_page).unwrap();
let mut adv_para = adv_c1.create_map().unwrap();
adv_para
.insert("sys:id".to_owned(), Any::String("para-adv".into()))
.unwrap();
adv_para
.insert("sys:flavour".to_owned(), Any::String("affine:paragraph".into()))
.unwrap();
let mut adv_text = adv_c1.create_text().unwrap();
adv_text.insert(0, "a".repeat(1_000)).unwrap();
let ref_val = object(vec![
("pageId", Any::String("target-adv-ref".into())),
("pad", Any::String("z".repeat(100 * 1024))),
]);
let mut ref_attrs = TextAttributes::new();
ref_attrs.insert("reference".to_owned(), ref_val);
adv_text.format(0, 1_000, ref_attrs).unwrap();
for i in (0..1_000u64).step_by(2) {
let mut bold = TextAttributes::new();
bold.insert("b".to_owned(), Any::True);
adv_text.format(i, 1, bold).unwrap();
}
adv_para.insert("prop:text".to_owned(), adv_text).unwrap();
adv_blocks.insert("para-adv".to_owned(), adv_para).unwrap();
let adv_c2 = y_octo::DocOptions::new().with_client_id(712).build();
let mut adv_scratch = adv_c2.get_or_create_map("scratch").unwrap();
adv_scratch.insert("x".to_owned(), Any::String("1".into())).unwrap();
let adv_sv = adv_c2.get_state_vector();
adv_scratch.insert("y".to_owned(), Any::String("2".into())).unwrap();
let adv_combined = y_octo::merge_updates_v1([
adv_c1.encode_update_v1().unwrap(),
adv_c2.encode_state_as_update_v1(&adv_sv).unwrap(),
])
.and_then(|u| u.encode_v1())
.unwrap();
assert!(matches!(
y_octo::ReadDoc::from_full_update_v1(adv_combined.clone()),
Err(y_octo::ReadError::IncompleteSnapshot(_))
));
let adv_proj = project_document_search(adv_combined, "doc-adv".to_owned())
.expect("adversarial incomplete snapshot page doc must extract inline references");
let adv_unit = unit(&adv_proj, "para-adv").expect("adversarial paragraph unit");
assert_eq!(adv_unit.text.len(), 1_000);
assert_eq!(adv_unit.ref_doc_ids, vec!["target-adv-ref".to_owned()]);
}
#[test]
fn projection_extracts_reader_text_and_references_per_flavour() {
let mut doc = TestDoc::new("doc-src", "Source");
+180 -91
View File
@@ -1,3 +1,5 @@
use std::time::{Duration, Instant};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use sqlx::{PgPool, Row};
@@ -10,7 +12,40 @@ use crate::provider::SearchProvider;
use crate::types::SearchTable;
use crate::{DOCUMENT_PROJECTION_FAILED, EMBEDDED_GENERATION_LOST, SCHEMA_FINGERPRINT, WORKSPACE_RECONCILE_FAILED};
pub const LIFECYCLE_LOCK_KEY: &str = "search-projection-lifecycle";
pub const LIFECYCLE_LOCK_KEY: &str = "search-projection-generation";
const DEFAULT_LOCK_TIMEOUT: Duration = Duration::from_secs(5);
const LOCK_POLL_INTERVAL: Duration = Duration::from_millis(50);
async fn begin_generation_write(
pool: &PgPool,
timeout: Duration,
context: &'static str,
) -> SearchResult<sqlx::Transaction<'static, sqlx::Postgres>> {
let deadline = Instant::now() + timeout;
loop {
let mut transaction = pool
.begin()
.await
.map_err(|error| SearchError::database(context, error))?;
let acquired: bool = sqlx::query_scalar("SELECT pg_try_advisory_xact_lock(hashtextextended($1, 0))")
.bind(LIFECYCLE_LOCK_KEY)
.fetch_one(&mut *transaction)
.await
.map_err(|error| SearchError::database(context, error))?;
if acquired {
return Ok(transaction);
}
transaction
.rollback()
.await
.map_err(|error| SearchError::database(context, error))?;
let now = Instant::now();
if now >= deadline {
return Err(SearchError::IndexNotReady);
}
tokio::time::sleep(LOCK_POLL_INTERVAL.min(deadline - now)).await;
}
}
#[derive(Clone, Debug)]
pub struct ActiveGeneration {
@@ -33,73 +68,124 @@ pub async fn ensure(
config: &SearchConfig,
remote: Option<&SearchProvider>,
rebuild_embedded: bool,
) -> SearchResult<ActiveGeneration> {
ensure_with_lock_timeout(pool, config, remote, rebuild_embedded, DEFAULT_LOCK_TIMEOUT).await
}
pub async fn ensure_with_lock_timeout(
pool: &PgPool,
config: &SearchConfig,
remote: Option<&SearchProvider>,
rebuild_embedded: bool,
lock_timeout: Duration,
) -> SearchResult<ActiveGeneration> {
let expected_config_hash = config_hash(config);
let expected_provider_identity = provider_identity(config);
let mut transaction = pool
.begin()
.await
.map_err(|error| SearchError::database("begin search generation", error))?;
sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))")
.bind(LIFECYCLE_LOCK_KEY)
.execute(&mut *transaction)
.await
.map_err(|error| SearchError::database("lock search generation lifecycle", error))?;
sqlx::query(
r#"UPDATE search_projection.generations
let steady_generation = if !rebuild_embedded {
let steady = sqlx::query(
r#"SELECT id, provider, config_hash, schema_version, manifest,
EXISTS(SELECT 1 FROM search_projection.generations WHERE state = 'building') AS has_building
FROM search_projection.generations
WHERE state = 'active'
ORDER BY activated_at DESC NULLS LAST
LIMIT 1"#,
)
.fetch_optional(pool)
.await
.map_err(|error| SearchError::database("load steady-state active search generation", error))?;
if let Some(row) = steady {
let has_building: bool = row
.try_get("has_building")
.map_err(|error| SearchError::database("decode building generation existence", error))?;
let provider: String = row
.try_get("provider")
.map_err(|error| SearchError::database("decode steady-state search provider", error))?;
let existing_config_hash: Vec<u8> = row
.try_get("config_hash")
.map_err(|error| SearchError::database("decode steady-state search config hash", error))?;
let schema_version: i32 = row
.try_get("schema_version")
.map_err(|error| SearchError::database("decode steady-state search schema version", error))?;
let manifest: Value = row
.try_get("manifest")
.map_err(|error| SearchError::database("decode steady-state search manifest", error))?;
if !has_building
&& provider == config.provider
&& existing_config_hash == expected_config_hash
&& schema_version == SCHEMA_FINGERPRINT
&& manifest.get("providerIdentity").and_then(Value::as_str) == Some(expected_provider_identity.as_str())
{
Some(decode(row)?)
} else {
None
}
} else {
None
}
} else {
None
};
let generation = if let Some(generation) = steady_generation {
generation
} else {
let mut transaction = begin_generation_write(pool, lock_timeout, "lock search generation lifecycle").await?;
sqlx::query(
r#"UPDATE search_projection.generations
SET manifest = jsonb_set(manifest, '{providerIdentity}', to_jsonb($1::text), true)
WHERE provider = $2 AND config_hash = $3 AND state IN ('building', 'active', 'draining')
AND NOT manifest ? 'providerIdentity'"#,
)
.bind(&expected_provider_identity)
.bind(&config.provider)
.bind(&expected_config_hash)
.execute(&mut *transaction)
.await
.map_err(|error| SearchError::database("backfill search provider identity", error))?;
)
.bind(&expected_provider_identity)
.bind(&config.provider)
.bind(&expected_config_hash)
.execute(&mut *transaction)
.await
.map_err(|error| SearchError::database("backfill search provider identity", error))?;
let existing = sqlx::query(
r#"SELECT id, provider, config_hash, schema_version, manifest, state
let existing = sqlx::query(
r#"SELECT id, provider, config_hash, schema_version, manifest, state
FROM search_projection.generations
WHERE state = 'building'
ORDER BY created_at DESC
LIMIT 1"#,
)
.fetch_optional(&mut *transaction)
.await
.map_err(|error| SearchError::database("load search generation", error))?;
)
.fetch_optional(&mut *transaction)
.await
.map_err(|error| SearchError::database("load search generation", error))?;
let generation = if let Some(row) = existing {
let provider: String = row
.try_get("provider")
.map_err(|error| SearchError::database("decode search generation provider", error))?;
let existing_config_hash: Vec<u8> = row
.try_get("config_hash")
.map_err(|error| SearchError::database("decode search generation config hash", error))?;
let schema_version: i32 = row
.try_get("schema_version")
.map_err(|error| SearchError::database("decode search generation schema version", error))?;
if provider != config.provider
|| existing_config_hash != expected_config_hash
|| schema_version != SCHEMA_FINGERPRINT
{
let id: Uuid = row
.try_get("id")
.map_err(|error| SearchError::database("decode superseded search generation id", error))?;
sqlx::query(
let generation = if let Some(row) = existing {
let provider: String = row
.try_get("provider")
.map_err(|error| SearchError::database("decode search generation provider", error))?;
let existing_config_hash: Vec<u8> = row
.try_get("config_hash")
.map_err(|error| SearchError::database("decode search generation config hash", error))?;
let schema_version: i32 = row
.try_get("schema_version")
.map_err(|error| SearchError::database("decode search generation schema version", error))?;
if provider != config.provider
|| existing_config_hash != expected_config_hash
|| schema_version != SCHEMA_FINGERPRINT
{
let id: Uuid = row
.try_get("id")
.map_err(|error| SearchError::database("decode superseded search generation id", error))?;
sqlx::query(
"UPDATE search_projection.generations SET state = 'failed', last_error = 'search generation superseded by configuration' WHERE id = $1 AND state = 'building'",
)
.bind(id)
.execute(&mut *transaction)
.await
.map_err(|error| SearchError::database("fail superseded search generation", error))?;
create_generation(&mut transaction, config, expected_config_hash.clone()).await?
} else if rebuild_embedded {
let id: Uuid = row
.try_get("id")
.map_err(|error| SearchError::database("decode search generation id", error))?;
sqlx::query(
create_generation(&mut transaction, config, expected_config_hash.clone()).await?
} else if rebuild_embedded {
let id: Uuid = row
.try_get("id")
.map_err(|error| SearchError::database("decode search generation id", error))?;
sqlx::query(
"UPDATE search_projection.generations SET state = 'failed', last_error = $2 WHERE id = $1 AND state = 'building'",
)
.bind(id)
@@ -107,47 +193,49 @@ pub async fn ensure(
.execute(&mut *transaction)
.await
.map_err(|error| SearchError::database("fail stale embedded generation", error))?;
create_generation(&mut transaction, config, expected_config_hash.clone()).await?
create_generation(&mut transaction, config, expected_config_hash.clone()).await?
} else {
decode(row)?
}
} else {
decode(row)?
}
} else {
let active = sqlx::query(
r#"SELECT id, provider, config_hash, schema_version, manifest
let active = sqlx::query(
r#"SELECT id, provider, config_hash, schema_version, manifest
FROM search_projection.generations
WHERE state = 'active'
ORDER BY activated_at DESC NULLS LAST LIMIT 1"#,
)
.fetch_optional(&mut *transaction)
.await
.map_err(|error| SearchError::database("load active search generation", error))?;
if let Some(row) = active {
let provider: String = row
.try_get("provider")
.map_err(|error| SearchError::database("decode active search provider", error))?;
let existing_config_hash: Vec<u8> = row
.try_get("config_hash")
.map_err(|error| SearchError::database("decode active search config hash", error))?;
let schema_version: i32 = row
.try_get("schema_version")
.map_err(|error| SearchError::database("decode active search schema version", error))?;
if !rebuild_embedded
&& provider == config.provider
&& existing_config_hash == expected_config_hash
&& schema_version == SCHEMA_FINGERPRINT
{
decode(row)?
)
.fetch_optional(&mut *transaction)
.await
.map_err(|error| SearchError::database("load active search generation", error))?;
if let Some(row) = active {
let provider: String = row
.try_get("provider")
.map_err(|error| SearchError::database("decode active search provider", error))?;
let existing_config_hash: Vec<u8> = row
.try_get("config_hash")
.map_err(|error| SearchError::database("decode active search config hash", error))?;
let schema_version: i32 = row
.try_get("schema_version")
.map_err(|error| SearchError::database("decode active search schema version", error))?;
if !rebuild_embedded
&& provider == config.provider
&& existing_config_hash == expected_config_hash
&& schema_version == SCHEMA_FINGERPRINT
{
decode(row)?
} else {
create_or_reject_failed(&mut transaction, config, expected_config_hash.clone()).await?
}
} else {
create_or_reject_failed(&mut transaction, config, expected_config_hash.clone()).await?
}
} else {
create_or_reject_failed(&mut transaction, config, expected_config_hash.clone()).await?
}
};
transaction
.commit()
.await
.map_err(|error| SearchError::database("commit search generation", error))?;
generation
};
transaction
.commit()
.await
.map_err(|error| SearchError::database("commit search generation", error))?;
for table in [SearchTable::Doc, SearchTable::Block] {
let physical_table = match generation.physical_table(table) {
@@ -305,16 +393,17 @@ async fn create_or_reject_failed(
}
pub async fn activate(pool: &PgPool, generation: &ActiveGeneration, config: &SearchConfig) -> SearchResult<()> {
activate_with_lock_timeout(pool, generation, config, DEFAULT_LOCK_TIMEOUT).await
}
pub async fn activate_with_lock_timeout(
pool: &PgPool,
generation: &ActiveGeneration,
config: &SearchConfig,
lock_timeout: Duration,
) -> SearchResult<()> {
let expected_config_hash = config_hash(config);
let mut transaction = pool
.begin()
.await
.map_err(|error| SearchError::database("begin search generation activation", error))?;
sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))")
.bind(LIFECYCLE_LOCK_KEY)
.execute(&mut *transaction)
.await
.map_err(|error| SearchError::database("lock search generation activation", error))?;
let mut transaction = begin_generation_write(pool, lock_timeout, "lock search generation activation").await?;
let row = sqlx::query(
r#"SELECT generation.state, generation.provider, generation.config_hash, generation.schema_version,
@@ -158,7 +158,7 @@ fn cross_workspace_writes_do_not_block_on_generation_or_gc() {
.unwrap();
assert!(matches!(orphan_hw, OrphanGcFence::Ready(_)));
// 2) Generation ensure (search-projection-lifecycle) succeeds immediately.
// 2) Generation ensure (search-projection-generation) succeeds immediately under lockless_v2.
tokio::time::timeout(Duration::from_secs(2), runtime.initialize())
.await
.expect("generation ensure must not block on workspace A write")
@@ -2199,3 +2199,158 @@ fn bridge_window_defers_deleted_workspace_gc_until_lease_recovers() {
db.pool().close().await;
});
}
#[test]
fn generation_ensure_steady_state_is_lock_free_and_lifecycle_lock_is_non_queueing() {
let _xmin_guard = PRIVATE_CLUSTER_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let cluster = private_cluster();
let empty = EmptyDbGuard::create(&cluster, "s_genlock");
test_runtime().block_on(async {
let db = setup_db(&empty.url).await;
let pool = db.pool().clone();
let config = enabled_search_config();
// 1. Contention + non-queueing check: when tx_shared_1 holds shared lock on
// 'search-projection-generation', cold-start ensure_with_lock_timeout returns IndexNotReady
// without queueing behind PG's exclusive lock waiter queue, so tx_shared_2 acquires the
// shared lock immediately.
let mut tx_shared_1 = pool.begin().await.unwrap();
sqlx::query("SELECT pg_advisory_xact_lock_shared(hashtextextended($1, 0))")
.bind("search-projection-generation")
.execute(&mut *tx_shared_1)
.await
.unwrap();
// First verify deterministically that ensure_with_lock_timeout fails with IndexNotReady
// under shared lock contention.
let quick_err =
server_search::generation::ensure_with_lock_timeout(&pool, &config, None, false, Duration::from_millis(80))
.await
.expect_err("ensure must return IndexNotReady while shared lock is held");
assert!(
matches!(quick_err, SearchError::IndexNotReady),
"expected IndexNotReady, got: {quick_err:?}"
);
// Then run ensure_with_lock_timeout concurrently with a second shared lock acquisition
// and verify tx_shared_2 is never blocked behind an exclusive lock waiter.
let ensure_pool = pool.clone();
let ensure_cfg = config.clone();
let ensure_handle = tokio::spawn(async move {
server_search::generation::ensure_with_lock_timeout(
&ensure_pool,
&ensure_cfg,
None,
false,
Duration::from_millis(300),
)
.await
});
tokio::task::yield_now().await;
let mut tx_shared_2 = pool.begin().await.unwrap();
sqlx::query("SET LOCAL lock_timeout = '100ms'")
.execute(&mut *tx_shared_2)
.await
.unwrap();
sqlx::query("SELECT pg_advisory_xact_lock_shared(hashtextextended($1, 0))")
.bind("search-projection-generation")
.execute(&mut *tx_shared_2)
.await
.expect("second shared writer must never be blocked by non-queueing generation ensure");
let ensure_err = ensure_handle
.await
.expect("join ensure")
.expect_err("ensure must return IndexNotReady while shared lock is held");
assert!(
matches!(ensure_err, SearchError::IndexNotReady),
"expected IndexNotReady, got: {ensure_err:?}"
);
tx_shared_2.rollback().await.unwrap();
tx_shared_1.rollback().await.unwrap();
// After releasing shared locks, ensure creates the generation immediately.
let building_gen = server_search::generation::ensure(&pool, &config, None, false)
.await
.expect("ensure must succeed after shared locks release");
// 2. Mark generation scan complete; verify activate_with_lock_timeout returns IndexNotReady
// when exclusive lock is held, and activates immediately once released.
sqlx::query(
"UPDATE search_projection.generations
SET scan_high_water_sid = 0, scan_cursor_sid = 0
WHERE id = $1",
)
.bind(building_gen.id)
.execute(&pool)
.await
.unwrap();
let mut tx_excl = pool.begin().await.unwrap();
sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))")
.bind("search-projection-generation")
.execute(&mut *tx_excl)
.await
.unwrap();
let act_err =
server_search::generation::activate_with_lock_timeout(&pool, &building_gen, &config, Duration::from_millis(150))
.await
.expect_err("activate must return IndexNotReady while exclusive lock is held");
assert!(
matches!(act_err, SearchError::IndexNotReady),
"expected IndexNotReady on activate, got: {act_err:?}"
);
tx_excl.rollback().await.unwrap();
server_search::generation::activate(&pool, &building_gen, &config)
.await
.expect("activate must succeed after lock release");
let state: String = sqlx::query_scalar("SELECT state FROM search_projection.generations WHERE id = $1")
.bind(building_gen.id)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(state, "active");
// 3. Steady-state lock-free check: initialize runtime so embedded index has the active
// generation, hold an EXCLUSIVE lock on 'search-projection-generation' on another
// connection, and assert runtime.reconcile_pending(50) finishes in < 1s via fast path.
let runtime =
SearchRuntime::new(pool.clone(), Arc::new(CommunityQuotaGate::new()), config).expect("build search runtime");
runtime.initialize().await.expect("initialize runtime");
// Beat 1 records fenceXid, beat 2 latches scan_high_water_sid, beat 3 activates the empty generation.
runtime.reconcile_pending(50).await.unwrap();
runtime.reconcile_pending(50).await.unwrap();
runtime.reconcile_pending(50).await.unwrap();
runtime
.active_generation()
.await
.expect("embedded generation must be active after 3 deterministic reconcile beats");
let mut tx_steady_lock = pool.begin().await.unwrap();
sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))")
.bind("search-projection-generation")
.execute(&mut *tx_steady_lock)
.await
.unwrap();
let started = std::time::Instant::now();
tokio::time::timeout(Duration::from_secs(1), runtime.reconcile_pending(50))
.await
.expect("steady-state reconcile_pending must not wait on search-projection-generation")
.expect("steady-state reconcile_pending must succeed");
assert!(
started.elapsed() < Duration::from_secs(1),
"steady-state reconcile_pending took {:?}",
started.elapsed()
);
tx_steady_lock.rollback().await.unwrap();
db.pool().close().await;
});
}
@@ -2,21 +2,20 @@
//! Lazy migration of the legacy workspace root doc `meta.pages` identities and
//! trash flags into `workspace_pages`, run once per workspace.
use std::collections::BTreeMap;
use serde_json::json;
use server_db::WorkloadTier;
use server_domain::doc_meta::{
LegacyRootDecodeError, LifecycleRootMigrationOutcome, check_lifecycle_root_bytes_in,
extract_legacy_root_pages_with_limits, merge_and_decode_lifecycle_root_pages,
};
use super::{
LegacyRootPage, SyncError, SyncStorage, WORKSPACE_LIFECYCLE_MIGRATION_READ_LIMITS, compute_source_revision,
invalidate_workspace_inventory_in, is_empty_doc_bin, is_ordinary_workspace_doc, load_workspace_doc_parts_in,
lock_workspace_doc_update, lock_workspace_storage_exclusive,
invalidate_workspace_inventory_in, load_workspace_doc_parts_in, lock_workspace_doc_update,
lock_workspace_storage_exclusive,
};
pub(super) enum LifecycleRootDecodeError {
ResourceLimit(String),
InvalidMetadata(String),
}
pub(super) type LifecycleRootDecodeError = LegacyRootDecodeError;
/// Extracts legacy `{ id, trash }` entries from a workspace root doc's
/// `meta.pages` array, matching `packages/backend/native/src/doc/mod.rs`.
@@ -37,107 +36,15 @@ pub(super) fn extract_workspace_lifecycle_root_pages_with_limits(
bytes: &[u8],
limits: y_octo::ReadLimits,
) -> Result<Vec<LegacyRootPage>, LifecycleRootDecodeError> {
if is_empty_doc_bin(bytes) {
return Ok(Vec::new());
}
match y_octo::ReadDoc::from_full_update_v1_with_limits(bytes.to_vec(), limits) {
Ok(doc) => Ok(extract_lifecycle_pages_from_read_doc(&doc)),
Err(y_octo::ReadError::IncompleteSnapshot(_)) => {
let doc = y_octo::Doc::try_from_binary_v1(bytes)
.map_err(|e| LifecycleRootDecodeError::InvalidMetadata(format!("root doc fallback decode failed: {e}")))?;
Ok(extract_lifecycle_pages_from_doc(&doc))
}
Err(y_octo::ReadError::ResourceLimit(detail)) => Err(LifecycleRootDecodeError::ResourceLimit(detail.to_owned())),
Err(err) => Err(LifecycleRootDecodeError::InvalidMetadata(err.to_string())),
}
}
fn push_lifecycle_page(out: &mut Vec<LegacyRootPage>, doc_id: &str, trashed: bool) {
if !doc_id.trim().is_empty() {
out.push(LegacyRootPage {
doc_id: doc_id.to_owned(),
trashed,
});
}
}
fn push_lifecycle_page_from_read_any(out: &mut Vec<LegacyRootPage>, 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(out, doc_id, trashed);
}
}
fn push_lifecycle_page_from_object(out: &mut Vec<LegacyRootPage>, 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(out, doc_id, trashed);
}
}
fn extract_lifecycle_pages_from_read_doc(doc: &y_octo::ReadDoc) -> Vec<LegacyRootPage> {
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<LegacyRootPage> {
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
extract_legacy_root_pages_with_limits(bytes, limits).map(|pages| {
pages
.into_iter()
.map(|p| LegacyRootPage {
doc_id: p.doc_id,
trashed: p.trashed,
})
.collect()
})
}
impl SyncStorage {
@@ -230,44 +137,36 @@ impl SyncStorage {
return Ok(());
}
if let Err(detail) = check_lifecycle_root_bytes_in(tx.tx_mut(), workspace_id, limits.max_input_bytes)
.await
.map_err(|e| SyncError::Internal(e.to_string()))?
{
return Err(SyncError::Internal(format!(
"workspace lifecycle root doc exceeded read limits: {detail}"
)));
}
let parts = load_workspace_doc_parts_in(tx.tx_mut(), workspace_id, workspace_id).await?;
let source_rev = compute_source_revision(&parts);
let (root_status, legacy_pages): (&'static str, Vec<LegacyRootPage>) = if parts.is_empty() {
let (root_status, deduped_pages): (&'static str, Vec<(String, bool)>) = if parts.is_empty() {
("absent", Vec::new())
} else {
let ws_id = workspace_id.to_owned();
let blobs: Vec<Vec<u8>> = parts.into_iter().map(|p| p.blob).collect();
tokio::task::spawn_blocking(move || {
let slices: Vec<&[u8]> = blobs.iter().map(Vec::as_slice).collect();
let Ok(merged) = y_octo::merge_updates_v1(slices).and_then(|u| u.encode_v1()) else {
return Ok(("invalid_binary", Vec::new()));
};
match extract_workspace_lifecycle_root_pages_with_limits(&merged, limits) {
Ok(pages) => Ok(("decoded", pages)),
Err(LifecycleRootDecodeError::InvalidMetadata(_)) => Ok(("invalid_metadata", Vec::new())),
Err(LifecycleRootDecodeError::ResourceLimit(detail)) => Err(SyncError::Internal(format!(
tokio::task::spawn_blocking(
move || match merge_and_decode_lifecycle_root_pages(&ws_id, None, blobs, limits) {
LifecycleRootMigrationOutcome::Completed { root_status, pages } => Ok((root_status, pages)),
LifecycleRootMigrationOutcome::ResourceLimit(detail) => Err(SyncError::Internal(format!(
"workspace lifecycle root doc exceeded read limits: {detail}"
))),
}
})
},
)
.await
.map_err(|e| SyncError::Internal(format!("root lifecycle decode task failed: {e}")))??
};
// Deduplicate ordinary docs; duplicate entries clear their trash state (workspace_state.rs:199-211).
let mut unique = BTreeMap::<String, Option<bool>>::new();
for page in legacy_pages {
if is_ordinary_workspace_doc(workspace_id, &page.doc_id) {
unique
.entry(page.doc_id)
.and_modify(|state| *state = None)
.or_insert(Some(page.trashed));
}
}
let (doc_ids, trashed): (Vec<String>, Vec<bool>) = unique
.into_iter()
.filter_map(|(id, state)| state.map(|is_trashed| (id, is_trashed)))
.unzip();
let (doc_ids, trashed): (Vec<String>, Vec<bool>) = deduped_pages.into_iter().unzip();
if !doc_ids.is_empty() {
sqlx::query(
+38 -32
View File
@@ -82,10 +82,6 @@ pub struct LegacyRootPage {
pub trashed: bool,
}
fn is_empty_doc_bin(bin: &[u8]) -> bool {
bin.is_empty() || (bin.len() == 1 && bin[0] == 0) || (bin.len() == 2 && bin[0] == 0 && bin[1] == 0)
}
/// Pure `y-octo` helper: merges ordered updates and computes `(missing, state)`
/// matching `packages/backend/server/src/core/doc/reader.ts` and
/// `packages/backend/native/src/runtime/storage_runtime/current_doc.rs` 1:1.
@@ -106,16 +102,7 @@ pub fn merge_and_diff_doc(updates: &[&[u8]], state_vector: Option<&[u8]>) -> Res
Ok((missing, state))
}
/// Dedicated read limits for workspace lifecycle migration, matching
/// `packages/backend/native/src/doc/mod.rs`.
pub 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,
};
pub use server_domain::doc_meta::WORKSPACE_LIFECYCLE_MIGRATION_READ_LIMITS;
#[derive(Default)]
struct RejectZeroLengthSink {
@@ -2604,25 +2591,44 @@ mod realtime_snapshot_tests {
.await
.unwrap();
let tiny_limits = y_octo::ReadLimits {
max_structs: 1,
..y_octo::ReadLimits::default()
};
let err = storage
.ensure_workspace_lifecycle_with_limits(&ws_id, 2, tiny_limits)
.await
.unwrap_err();
assert!(matches!(err, SyncError::Internal(ref msg) if msg.contains("read limits")));
for (label, tight_limits) in [
(
"max_structs",
y_octo::ReadLimits {
max_structs: 1,
..y_octo::ReadLimits::default()
},
),
(
"max_input_bytes",
y_octo::ReadLimits {
max_input_bytes: 16,
..y_octo::ReadLimits::default()
},
),
] {
let err = storage
.ensure_workspace_lifecycle_with_limits(&ws_id, 2, tight_limits)
.await
.unwrap_err();
assert!(
matches!(err, SyncError::Internal(ref msg) if msg.contains("read limits")),
"{label}: expected read limits error, got: {err:?}"
);
let completed: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM storage_reconciliation_checkpoints \
WHERE kind = 'workspace_doc_lifecycle' AND scope = $1 AND status = 'completed')",
)
.bind(&ws_id)
.fetch_one(db.pool())
.await
.unwrap();
assert!(!completed, "ResourceLimit must roll back without writing completed checkpoint");
let completed: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM storage_reconciliation_checkpoints \
WHERE kind = 'workspace_doc_lifecycle' AND scope = $1 AND status = 'completed')",
)
.bind(&ws_id)
.fetch_one(db.pool())
.await
.unwrap();
assert!(
!completed,
"{label}: ResourceLimit must roll back without writing completed checkpoint"
);
}
// Retrying the same workspace under normal migration limits succeeds, records completed,
// and persists both active and trashed page lifecycle states.
@@ -514,8 +514,12 @@ fn lifecycle_root_pages_decode_empty_multi_increment_and_zero_len_deleted_frames
}]
);
// Dedicated workspace lifecycle migration budget matches the 16M struct contract.
// Workspace lifecycle migration budget matches native/src/doc/mod.rs (16M structs).
assert_eq!(WORKSPACE_LIFECYCLE_MIGRATION_READ_LIMITS.max_structs, 16_000_000);
assert_ne!(
WORKSPACE_LIFECYCLE_MIGRATION_READ_LIMITS.max_structs,
y_octo::ReadLimits::default().max_structs
);
}
#[test]
@@ -1,14 +1,18 @@
//! Periodic public background maintenance workers.
use std::collections::{BTreeMap, HashSet};
use std::collections::HashSet;
use std::sync::atomic::{AtomicI64, Ordering};
use serde_json::json;
use server_db::{ServerDb, TieredConn, TieredTx, WorkloadTier};
use server_domain::doc_meta::{
LifecycleRootMigrationOutcome, WORKSPACE_LIFECYCLE_MIGRATION_READ_LIMITS, check_lifecycle_root_bytes_in,
merge_and_decode_lifecycle_root_pages,
};
use server_domain::events::{EventBusPublisher, InvalidationHintV1, InvalidationPublisher};
use server_domain::yjs_read::run_with_doc_decode_permit;
use server_types::DomainError;
use sha2::{Digest as _, Sha256};
use y_octo::{Any, Doc, Value as YValue};
use crate::CancellationToken;
@@ -83,44 +87,6 @@ async fn load_root_doc_parts(tx: &mut PgTx<'_>, ws_id: &str) -> Result<(Option<V
.map_err(db_err("load root updates"))?;
Ok((snap, upds))
}
fn decode_root_pages(
ws_id: &str,
snapshot: &Option<Vec<u8>>,
updates: &[Vec<u8>],
) -> (Vec<(String, bool)>, &'static str) {
if snapshot.is_none() && updates.is_empty() {
return (Vec::new(), "absent");
}
let mut doc = Doc::default();
for b in snapshot.iter().chain(updates.iter()) {
if !b.is_empty() && doc.apply_update_from_binary_v1(b).is_err() {
return (Vec::new(), "invalid_binary");
}
}
let Ok(meta) = doc.get_or_create_map("meta") else {
return (Vec::new(), "decoded");
};
let Some(YValue::Array(pages)) = meta.get("pages") else {
return (Vec::new(), "decoded");
};
let mut unique = BTreeMap::<String, Option<bool>>::new();
for item in pages.iter() {
if let YValue::Map(page) = item
&& let Some(YValue::Any(Any::String(doc_id))) = page.get("id")
&& !doc_id.is_empty()
&& doc_id != ws_id
&& !doc_id.starts_with("db$")
&& !doc_id.starts_with("userdata$")
{
let trashed = matches!(page.get("trash"), Some(YValue::Any(Any::True)));
unique.entry(doc_id).and_modify(|s| *s = None).or_insert(Some(trashed));
}
}
(
unique.into_iter().filter_map(|(id, st)| st.map(|t| (id, t))).collect(),
"decoded",
)
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct LifecycleMigrationReport {
pub migrated_workspaces: usize,
@@ -130,6 +96,22 @@ pub async fn advance_workspace_lifecycle_migrations(
batch_limit: i64,
invalidation: Option<&dyn InvalidationPublisher>,
cancel: &CancellationToken,
) -> Result<LifecycleMigrationReport, DomainError> {
advance_workspace_lifecycle_migrations_with_limits(
db,
batch_limit,
invalidation,
cancel,
WORKSPACE_LIFECYCLE_MIGRATION_READ_LIMITS,
)
.await
}
pub async fn advance_workspace_lifecycle_migrations_with_limits(
db: &ServerDb,
batch_limit: i64,
invalidation: Option<&dyn InvalidationPublisher>,
cancel: &CancellationToken,
limits: y_octo::ReadLimits,
) -> Result<LifecycleMigrationReport, DomainError> {
let limit = batch_limit.clamp(1, 1000);
let mut report = LifecycleMigrationReport::default();
@@ -176,10 +158,40 @@ pub async fn advance_workspace_lifecycle_migrations(
"SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY",
)
.await?;
if let Err(detail) = check_lifecycle_root_bytes_in(rtx.tx_mut(), ws_id, limits.max_input_bytes).await? {
tracing::warn!(
workspace_id = %ws_id,
error = %detail,
"skipping workspace root doc exceeding lifecycle read limits"
);
commit_tx(rtx).await?;
continue;
}
let (snapshot, updates) = load_root_doc_parts(rtx.tx_mut(), ws_id).await?;
let source_rev = compute_source_revision(&snapshot, &updates);
let (docs, root_status) = decode_root_pages(ws_id, &snapshot, &updates);
commit_tx(rtx).await?;
let source_rev = compute_source_revision(&snapshot, &updates);
let ws_id_owned = ws_id.clone();
let limits_for_decode = limits.clone();
let outcome = run_with_doc_decode_permit(move || {
Ok(merge_and_decode_lifecycle_root_pages(
&ws_id_owned,
snapshot,
updates,
limits_for_decode,
))
})
.await?;
let (docs, root_status) = match outcome {
LifecycleRootMigrationOutcome::Completed { root_status, pages } => (pages, root_status),
LifecycleRootMigrationOutcome::ResourceLimit(detail) => {
tracing::warn!(
workspace_id = %ws_id,
error = %detail,
"skipping workspace root doc exceeding lifecycle read limits"
);
continue;
}
};
let mut wtx = long_tx(db).await?;
set_tx(wtx.tx_mut(), "SET LOCAL lock_timeout = '250ms'").await?;
let k1 = format!("storage-workspace:{ws_id}");
@@ -209,6 +221,15 @@ pub async fn advance_workspace_lifecycle_migrations(
commit_tx(wtx).await?;
continue;
}
if let Err(detail) = check_lifecycle_root_bytes_in(wtx.tx_mut(), ws_id, limits.max_input_bytes).await? {
tracing::warn!(
workspace_id = %ws_id,
error = %detail,
"skipping workspace root doc exceeding lifecycle read limits during commit verification"
);
let _ = wtx.rollback().await;
continue;
}
let (cur_snap, cur_upds) = load_root_doc_parts(wtx.tx_mut(), ws_id).await?;
if compute_source_revision(&cur_snap, &cur_upds) != source_rev {
let _ = wtx.rollback().await;
@@ -14,8 +14,9 @@ use server_domain::events::{EventBusEnvelopeV1, EventBusPublisher};
use server_types::{DomainError, ServerRole};
use server_worker::CancellationToken;
use server_worker::maintenance::{
advance_workspace_lifecycle_migrations, cleanup_expired_notifications, cleanup_expired_runtime_housekeeping,
cleanup_mail_deliveries_and_skip_disabled, recalibrate_workspace_stats, refresh_dirty_workspace_stats,
advance_workspace_lifecycle_migrations, advance_workspace_lifecycle_migrations_with_limits,
cleanup_expired_notifications, cleanup_expired_runtime_housekeeping, cleanup_mail_deliveries_and_skip_disabled,
recalibrate_workspace_stats, refresh_dirty_workspace_stats,
};
use test_db_harness::{
migrations::MigrationSet,
@@ -278,3 +279,115 @@ fn background_maintenance_workers_are_correct_and_idempotent() {
db.pool().close().await;
});
}
#[test]
fn lifecycle_migration_skips_resource_limit_without_completed_checkpoint_and_recovers() {
let lease = leased_0275_database();
let db_url = lease.url().to_owned();
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()
.unwrap();
rt.block_on(async move {
let db = connect_db(&db_url).await;
let cancel = CancellationToken::new();
sqlx::query("INSERT INTO workspaces (id, name) VALUES ('ws-limit', 'Limit WS')")
.execute(db.pool())
.await
.unwrap();
sqlx::query(
"INSERT INTO storage_reconciliation_checkpoints (kind, scope, status) \
VALUES ('workspace_doc_lifecycle_activation', 'global', 'active')",
)
.execute(db.pool())
.await
.unwrap();
let root_bin = build_root_doc_with_trashed_page("doc-active", "doc-trashed");
sqlx::query(
"INSERT INTO snapshots (workspace_id, guid, blob, updated_at) VALUES ('ws-limit', 'ws-limit', $1, now())",
)
.bind(&root_bin)
.execute(db.pool())
.await
.unwrap();
// Both decode-phase (max_structs) and SQL-precheck (max_input_bytes) ResourceLimit failures
// must skip the workspace without writing a completed checkpoint or mutating workspace_pages.
for (label, tight_limits) in [
(
"max_structs",
y_octo::ReadLimits {
max_structs: 1,
..y_octo::ReadLimits::default()
},
),
(
"max_input_bytes",
y_octo::ReadLimits {
max_input_bytes: 16,
..y_octo::ReadLimits::default()
},
),
] {
let rep = advance_workspace_lifecycle_migrations_with_limits(&db, 100, None, &cancel, tight_limits)
.await
.unwrap();
assert_eq!(
rep.migrated_workspaces, 0,
"{label}: ResourceLimit must not mark workspace migrated"
);
let completed: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM storage_reconciliation_checkpoints \
WHERE kind='workspace_doc_lifecycle' AND scope='ws-limit' AND status='completed')",
)
.fetch_one(db.pool())
.await
.unwrap();
assert!(!completed, "{label}: ResourceLimit must not write completed checkpoint");
let page_rows: i64 =
sqlx::query_scalar("SELECT COUNT(*)::bigint FROM workspace_pages WHERE workspace_id='ws-limit'")
.fetch_one(db.pool())
.await
.unwrap();
assert_eq!(page_rows, 0, "{label}: workspace_pages must remain untouched");
}
// Retrying under default WORKSPACE_LIFECYCLE_MIGRATION_READ_LIMITS completes cleanly and
// preserves both active doc identity and trashed page state.
let recovered = advance_workspace_lifecycle_migrations(&db, 100, None, &cancel)
.await
.unwrap();
assert_eq!(recovered.migrated_workspaces, 1);
let completed: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM storage_reconciliation_checkpoints \
WHERE kind='workspace_doc_lifecycle' AND scope='ws-limit' AND status='completed')",
)
.fetch_one(db.pool())
.await
.unwrap();
assert!(completed);
let retained_active: i64 =
sqlx::query_scalar("SELECT COUNT(*)::bigint FROM updates WHERE workspace_id='ws-limit' AND guid='doc-active'")
.fetch_one(db.pool())
.await
.unwrap();
assert_eq!(retained_active, 1);
let trashed_state: String = sqlx::query_scalar(
"SELECT lifecycle_state::text FROM workspace_pages WHERE workspace_id='ws-limit' AND page_id='doc-trashed'",
)
.fetch_one(db.pool())
.await
.unwrap();
assert_eq!(trashed_state, "trashed");
db.pool().close().await;
});
}