mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-05 19:25:00 +03:00
feat(store): integrate affine-store into frontend workspace and harden sync
Integrate `packages/common/store` (`affine-store`) into the unified `packages/frontend` workspace and close cross-client compatibility and crash-recovery invariants against `0.27.5`: - Encode page creation identity via `PageIdSource` and `CreateDocId` (`DerivedFromOp` vs `Explicit`), derive deterministic 10-character URL-safe NanoIDs from `(space_id, op_id)` without sidecar tables or extra keys in shared Yjs `meta.pages`, and reject `page_id` collisions with the root `space_id`. - Keep `DocMode::Page` writing only the root document, require `db$docProperties` to be resolved before non-`Page` creation (returning `StoreError::DbTableNotResolved` so retry intent survives restarts), gate explicit non-`Page` crash-replay backfill on a client-local `export_explicit_create_journal` / `import_explicit_create_journal` record so legacy `0.27.5` pages without `DocProperties` rows keep `DocMode::Page`, preserve existing live or soft-deleted `DocProperties` rows independently of root page repair, and start `SqliteDocStorage::push_updates_batch` with `BEGIN IMMEDIATE` to prevent `SQLITE_BUSY_SNAPSHOT` on pooled WAL connections. - Capture unacknowledged `in_flight` and deferred `JoinDocs` updates in `SpaceSyncEngine::snapshot()` ahead of `offline_queue` while keeping live local writes gated on `waiting_for_id_converter`. - Wire `vars.NP_ALLOW_PERF_BOOTSTRAP` in `native-playground.yml` and document the three `perf/accepted.json` lifecycle actions in `packages/frontend/AGENTS.md`.
This commit is contained in:
1 parent
452828f66b
commit
78ef5e6f7f
29 files changed
+11151
-23
No files matched your search
@@ -277,6 +277,7 @@ jobs:
|
||||
run: |
|
||||
cargo check --locked -p ui -p playground --target wasm32-unknown-unknown
|
||||
cargo check --locked -p blocksuite-playground-doc --no-default-features --target wasm32-unknown-unknown
|
||||
cargo check --locked -p affine-store --no-default-features --target wasm32-unknown-unknown
|
||||
|
||||
headless-linux-and-perf:
|
||||
name: Headless Linux, Web Smoke & Perf
|
||||
@@ -369,6 +370,7 @@ jobs:
|
||||
- name: Compare against rolling N-3 baseline
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
NP_ALLOW_PERF_BOOTSTRAP: ${{ vars.NP_ALLOW_PERF_BOOTSTRAP }}
|
||||
run: |
|
||||
test -f perf/compare-n3.mjs
|
||||
STRICT_PERF_FLAG="--require-n3"
|
||||
|
||||
@@ -1,17 +1,44 @@
|
||||
# Working in `packages/common/store/` (for agents)
|
||||
|
||||
`packages/common/store/` holds the client storage and sans-I/O sync domain crate.
|
||||
`packages/common/store/` (`affine-store`) holds the client storage and sans-I/O sync domain crate.
|
||||
This directory belongs to the client Cargo workspace rooted at `packages/frontend/Cargo.toml`.
|
||||
|
||||
## Domain boundaries and invariants
|
||||
|
||||
- `packages/common/store/` declares `#![forbid(unsafe_code)]` and has zero GUI or platform dependencies.
|
||||
- Keep `#![forbid(unsafe_code)]` at the crate root.
|
||||
Never depend on `ui`, `wgpu`, `objc2`, or `web-sys` rendering types.
|
||||
|
||||
- Keep `rust-toolchain.toml` (`1.98.1` with `wasm32-unknown-unknown`) and `rustfmt.toml` (`edition = "2024"`) byte-identical to `packages/frontend/`.
|
||||
|
||||
- Do not add `package.json` or a standalone `Cargo.lock` to this directory.
|
||||
|
||||
- Do not enable `sqlx` `macros`.
|
||||
Do not depend on `packages/frontend/native/schema` across workspaces.
|
||||
|
||||
- This crate is the sole writer for AFFiNE root workspace metadata (`meta.pages` and `spaces[pageId]`) and workspace SQLite/IndexedDB tables.
|
||||
It exposes `WorkspaceDirectory` as a store-domain query and mutation service, and does not define editor port traits.
|
||||
When recovering an existing workspace via `WorkspaceDb::from_root_update_v1`, load `db$docProperties` via `load_db_table` or confirm its absence via `mark_db_table_absent` before calling non-`Page` `WorkspaceDirectory::create_doc` (which otherwise returns `StoreError::DbTableNotResolved` so retry intent survives restarts; explicit non-`Page` crash replays restore their client-local journal via `import_explicit_create_journal` so legacy `0.27.5` pages without `DocProperties` rows stay `Page`).
|
||||
|
||||
- Keep SQLite schema migrations frozen at the `0.27.5` five-step contract and share `<spaceId>.db` in place with legacy clients.
|
||||
Keep all five migration SQL strings byte-identical to `packages/frontend/native/schema/src/lib.rs`.
|
||||
|
||||
- Never scan a workspace directory for `*.db` files to discover local workspaces.
|
||||
Open only explicit allowlisted workspace identifiers.
|
||||
|
||||
- Never call system wall clocks (`SystemTime::now`, `Instant::now`, `Zoned::now`, `Timestamp::now`).
|
||||
Pass explicit timestamps or a `Clock` implementation.
|
||||
|
||||
- Keep every `.rs` file at or below 800 non-test lines and follow the module rules in `blocksuite/crates/AGENTS.md`.
|
||||
Keep both native and `wasm32-unknown-unknown` builds clean.
|
||||
|
||||
## Verification
|
||||
|
||||
Run commands inside `packages/frontend/` with root NAPI flags cleared:
|
||||
|
||||
```sh
|
||||
CARGO_ENCODED_RUSTFLAGS="" cargo fmt --all -- --check
|
||||
CARGO_ENCODED_RUSTFLAGS="" cargo clippy --locked --workspace --all-targets --features harness -- -D warnings
|
||||
CARGO_ENCODED_RUSTFLAGS="" cargo check --locked -p affine-store --no-default-features --target wasm32-unknown-unknown
|
||||
CARGO_ENCODED_RUSTFLAGS="" cargo test --locked -p affine-store
|
||||
./scripts/check-invariants.sh
|
||||
```
|
||||
@@ -0,0 +1,25 @@
|
||||
[package]
|
||||
name = "affine-store"
|
||||
workspace = "../../frontend"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
publish.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
base64.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
sha2.workspace = true
|
||||
thiserror.workspace = true
|
||||
y-octo.workspace = true
|
||||
|
||||
[target.'cfg(not(target_family = "wasm"))'.dependencies]
|
||||
chrono.workspace = true
|
||||
sqlx.workspace = true
|
||||
|
||||
[target.'cfg(not(target_family = "wasm"))'.dev-dependencies]
|
||||
tokio.workspace = true
|
||||
@@ -0,0 +1,304 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{error::StoreResult, id_converter::IdConverter};
|
||||
|
||||
/// Source context required by source-scoped Blob REST endpoints (`v0.27.5`).
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "camelCase")]
|
||||
pub enum BlobSource {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
CurrentDoc {
|
||||
workspace_id: String,
|
||||
doc_id: String,
|
||||
},
|
||||
#[serde(rename_all = "camelCase")]
|
||||
History {
|
||||
workspace_id: String,
|
||||
doc_id: String,
|
||||
timestamp_ms: i64,
|
||||
},
|
||||
}
|
||||
|
||||
impl BlobSource {
|
||||
pub fn source_type_str(&self) -> &'static str {
|
||||
match self {
|
||||
Self::CurrentDoc { .. } => "currentDoc",
|
||||
Self::History { .. } => "history",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn doc_id(&self) -> &str {
|
||||
match self {
|
||||
Self::CurrentDoc { doc_id, .. } | Self::History { doc_id, .. } => doc_id,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn timestamp_ms(&self) -> Option<i64> {
|
||||
match self {
|
||||
Self::CurrentDoc { .. } => None,
|
||||
Self::History { timestamp_ms, .. } => Some(*timestamp_ms),
|
||||
}
|
||||
}
|
||||
|
||||
fn with_doc_id(&self, next_doc_id: String) -> Self {
|
||||
match self {
|
||||
Self::CurrentDoc { workspace_id, .. } => Self::CurrentDoc {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: next_doc_id,
|
||||
},
|
||||
Self::History {
|
||||
workspace_id,
|
||||
timestamp_ms,
|
||||
..
|
||||
} => Self::History {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: next_doc_id,
|
||||
timestamp_ms: *timestamp_ms,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// HTTP method for transport-agnostic Blob REST requests.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum HttpMethod {
|
||||
Get,
|
||||
Put,
|
||||
}
|
||||
|
||||
/// Transport-agnostic HTTP request built by the source-scoped Blob REST codec.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct BlobHttpRequest {
|
||||
pub method: HttpMethod,
|
||||
pub path_and_query: String,
|
||||
pub headers: Vec<(String, String)>,
|
||||
pub body: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SourceBlobRecord {
|
||||
pub key: String,
|
||||
pub mime: String,
|
||||
pub size: i64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub created_at: Option<String>,
|
||||
pub source: BlobSource,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BlobManifestV1 {
|
||||
pub version: u32,
|
||||
pub entries: Vec<SourceBlobRecord>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ReadableBlobManifestV1 {
|
||||
pub version: u32,
|
||||
pub entries: Vec<SourceBlobRecord>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub next_cursor: Option<String>,
|
||||
}
|
||||
|
||||
/// Percent-encode a URI path or query component matching RFC 3986 unreserved characters.
|
||||
pub fn encode_uri_component(input: &str) -> String {
|
||||
let mut out = String::with_capacity(input.len());
|
||||
for byte in input.bytes() {
|
||||
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
|
||||
out.push(byte as char);
|
||||
} else {
|
||||
out.push('%');
|
||||
out.push(hex_upper(byte >> 4));
|
||||
out.push(hex_upper(byte & 0x0f));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn hex_upper(nibble: u8) -> char {
|
||||
match nibble {
|
||||
0..=9 => (b'0' + nibble) as char,
|
||||
10..=15 => (b'A' + (nibble - 10)) as char,
|
||||
_ => '0',
|
||||
}
|
||||
}
|
||||
|
||||
fn source_query_string(source: &BlobSource, id_converter: &IdConverter) -> String {
|
||||
let wire_doc_id = id_converter.new_id_to_old_id(source.doc_id());
|
||||
let mut query = format!(
|
||||
"sourceType={}&docId={}",
|
||||
encode_uri_component(source.source_type_str()),
|
||||
encode_uri_component(&wire_doc_id)
|
||||
);
|
||||
if let Some(ts) = source.timestamp_ms() {
|
||||
query.push_str(&format!("×tampMs={ts}"));
|
||||
}
|
||||
query
|
||||
}
|
||||
|
||||
fn normalize_manifest_entries(entries: &mut [SourceBlobRecord], id_converter: &IdConverter) {
|
||||
for entry in entries {
|
||||
let local_doc_id = id_converter.old_id_to_new_id(entry.source.doc_id());
|
||||
entry.source = entry.source.with_doc_id(local_doc_id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Build `GET /api/workspaces/:id/blobs/v1/:name?sourceType=...&docId=...[×tampMs=...]`
|
||||
/// with `source.doc_id()` converted to the server wire ID via `id_converter`.
|
||||
pub fn build_get_blob_request(
|
||||
workspace_id: &str,
|
||||
name: &str,
|
||||
source: &BlobSource,
|
||||
id_converter: &IdConverter,
|
||||
) -> BlobHttpRequest {
|
||||
let path_and_query = format!(
|
||||
"/api/workspaces/{}/blobs/v1/{}?{}",
|
||||
encode_uri_component(workspace_id),
|
||||
encode_uri_component(name),
|
||||
source_query_string(source, id_converter)
|
||||
);
|
||||
BlobHttpRequest {
|
||||
method: HttpMethod::Get,
|
||||
path_and_query,
|
||||
headers: vec![("cache-control".to_string(), "no-store".to_string())],
|
||||
body: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a direct presigned or multipart part `PUT` upload request using the URL and headers
|
||||
/// returned by the `createBlobUpload` / `blobUploadPartUrl` GraphQL mutations.
|
||||
pub fn build_presigned_put_request(
|
||||
upload_url: &str,
|
||||
headers: &[(String, String)],
|
||||
data: Vec<u8>,
|
||||
) -> BlobHttpRequest {
|
||||
BlobHttpRequest {
|
||||
method: HttpMethod::Put,
|
||||
path_and_query: upload_url.to_string(),
|
||||
headers: headers.to_vec(),
|
||||
body: Some(data),
|
||||
}
|
||||
}
|
||||
|
||||
/// Build `GET /api/workspaces/:id/blob-manifest/v1?sourceType=...&docId=...[×tampMs=...]`
|
||||
/// with `source.doc_id()` converted to the server wire ID via `id_converter`.
|
||||
pub fn build_blob_manifest_request(
|
||||
workspace_id: &str,
|
||||
source: &BlobSource,
|
||||
id_converter: &IdConverter,
|
||||
) -> BlobHttpRequest {
|
||||
let path_and_query = format!(
|
||||
"/api/workspaces/{}/blob-manifest/v1?{}",
|
||||
encode_uri_component(workspace_id),
|
||||
source_query_string(source, id_converter)
|
||||
);
|
||||
BlobHttpRequest {
|
||||
method: HttpMethod::Get,
|
||||
path_and_query,
|
||||
headers: vec![("cache-control".to_string(), "no-store".to_string())],
|
||||
body: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Build `GET /api/workspaces/:id/readable-blob-manifest/v1?limit=...[&cursor=...]`.
|
||||
pub fn build_readable_blob_manifest_request(
|
||||
workspace_id: &str,
|
||||
cursor: Option<&str>,
|
||||
limit: Option<u32>,
|
||||
) -> BlobHttpRequest {
|
||||
let limit = limit.unwrap_or(100);
|
||||
let mut query = format!("limit={limit}");
|
||||
if let Some(c) = cursor {
|
||||
query.push_str(&format!("&cursor={}", encode_uri_component(c)));
|
||||
}
|
||||
let path_and_query = format!(
|
||||
"/api/workspaces/{}/readable-blob-manifest/v1?{query}",
|
||||
encode_uri_component(workspace_id)
|
||||
);
|
||||
BlobHttpRequest {
|
||||
method: HttpMethod::Get,
|
||||
path_and_query,
|
||||
headers: vec![("cache-control".to_string(), "no-store".to_string())],
|
||||
body: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode `GET /api/workspaces/:id/blob-manifest/v1` and normalize wire `docId`s to local IDs.
|
||||
pub fn decode_blob_manifest_v1(
|
||||
body: &[u8],
|
||||
id_converter: &IdConverter,
|
||||
) -> StoreResult<BlobManifestV1> {
|
||||
let mut manifest: BlobManifestV1 = serde_json::from_slice(body)?;
|
||||
normalize_manifest_entries(&mut manifest.entries, id_converter);
|
||||
Ok(manifest)
|
||||
}
|
||||
|
||||
/// Decode `GET /api/workspaces/:id/readable-blob-manifest/v1` and normalize wire `docId`s to local IDs.
|
||||
pub fn decode_readable_blob_manifest_v1(
|
||||
body: &[u8],
|
||||
id_converter: &IdConverter,
|
||||
) -> StoreResult<ReadableBlobManifestV1> {
|
||||
let mut manifest: ReadableBlobManifestV1 = serde_json::from_slice(body)?;
|
||||
normalize_manifest_entries(&mut manifest.entries, id_converter);
|
||||
Ok(manifest)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn source_scoped_blob_requests_and_manifest_codecs_convert_ids_and_match_v0275() {
|
||||
let mut converter = IdConverter::new("ws-1");
|
||||
converter.register_page_mapping("page-local", "legacy-guid-1");
|
||||
|
||||
let current = BlobSource::CurrentDoc {
|
||||
workspace_id: "ws-1".into(),
|
||||
doc_id: "page-local".into(),
|
||||
};
|
||||
let get_req = build_get_blob_request("ws-1", "img+1.png", ¤t, &converter);
|
||||
assert_eq!(get_req.method, HttpMethod::Get);
|
||||
assert_eq!(
|
||||
get_req.path_and_query,
|
||||
"/api/workspaces/ws-1/blobs/v1/img%2B1.png?sourceType=currentDoc&docId=legacy-guid-1"
|
||||
);
|
||||
|
||||
let history = BlobSource::History {
|
||||
workspace_id: "ws-1".into(),
|
||||
doc_id: "page-local".into(),
|
||||
timestamp_ms: 1_700_000_000_000,
|
||||
};
|
||||
let manifest_req = build_blob_manifest_request("ws-1", &history, &converter);
|
||||
assert_eq!(
|
||||
manifest_req.path_and_query,
|
||||
"/api/workspaces/ws-1/blob-manifest/v1?sourceType=history&docId=legacy-guid-1×tampMs=1700000000000"
|
||||
);
|
||||
|
||||
let readable_req = build_readable_blob_manifest_request("ws-1", Some("cur=1"), Some(50));
|
||||
assert_eq!(
|
||||
readable_req.path_and_query,
|
||||
"/api/workspaces/ws-1/readable-blob-manifest/v1?limit=50&cursor=cur%3D1"
|
||||
);
|
||||
|
||||
let put_req = build_presigned_put_request(
|
||||
"https://s3.example.com/bucket/blob-9?sig=abc",
|
||||
&[("content-type".into(), "image/png".into())],
|
||||
vec![1, 2, 3],
|
||||
);
|
||||
assert_eq!(put_req.method, HttpMethod::Put);
|
||||
assert_eq!(put_req.body, Some(vec![1, 2, 3]));
|
||||
|
||||
let manifest_json = br#"{"version":1,"entries":[{"key":"b1","mime":"image/png","size":12,"source":{"type":"currentDoc","workspaceId":"ws-1","docId":"legacy-guid-1"}}],"nextCursor":"next-1"}"#;
|
||||
let parsed = decode_readable_blob_manifest_v1(manifest_json, &converter).unwrap();
|
||||
assert_eq!(parsed.version, 1);
|
||||
assert_eq!(parsed.entries.len(), 1);
|
||||
assert_eq!(parsed.entries[0].source.doc_id(), "page-local");
|
||||
assert_eq!(parsed.next_cursor.as_deref(), Some("next-1"));
|
||||
|
||||
let single_json = br#"{"version":1,"entries":[{"key":"b2","mime":"text/plain","size":4,"source":{"type":"history","workspaceId":"ws-1","docId":"db$ws-1$folders","timestampMs":42}}]}"#;
|
||||
let single = decode_blob_manifest_v1(single_json, &converter).unwrap();
|
||||
assert_eq!(single.entries[0].source.doc_id(), "db$folders");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
use std::sync::atomic::{AtomicI64, Ordering};
|
||||
|
||||
/// Deterministic millisecond clock for storage timestamps and sync timers.
|
||||
pub trait Clock: Send + Sync {
|
||||
/// Return the current timestamp in Unix epoch milliseconds.
|
||||
fn now_ms(&self) -> i64;
|
||||
}
|
||||
|
||||
/// Deterministic test and simulation clock controlled by explicit advances.
|
||||
#[derive(Debug)]
|
||||
pub struct ManualClock {
|
||||
now_ms: AtomicI64,
|
||||
}
|
||||
|
||||
impl ManualClock {
|
||||
/// Create a clock initialized at `start_ms`.
|
||||
pub fn new(start_ms: i64) -> Self {
|
||||
Self {
|
||||
now_ms: AtomicI64::new(start_ms),
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the clock to `value_ms`.
|
||||
pub fn set(&self, value_ms: i64) {
|
||||
self.now_ms.store(value_ms, Ordering::Release);
|
||||
}
|
||||
|
||||
/// Advance the clock by `delta_ms` and return the new time.
|
||||
pub fn advance(&self, delta_ms: i64) -> i64 {
|
||||
self.now_ms.fetch_add(delta_ms, Ordering::AcqRel) + delta_ms
|
||||
}
|
||||
}
|
||||
|
||||
impl Clock for ManualClock {
|
||||
fn now_ms(&self) -> i64 {
|
||||
self.now_ms.load(Ordering::Acquire)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn manual_clock_tracks_explicit_advances() {
|
||||
let clock = ManualClock::new(1_000);
|
||||
assert_eq!(clock.now_ms(), 1_000);
|
||||
assert_eq!(clock.advance(250), 1_250);
|
||||
assert_eq!(clock.now_ms(), 1_250);
|
||||
clock.set(9_000);
|
||||
assert_eq!(clock.now_ms(), 9_000);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,48 @@
|
||||
use thiserror::Error;
|
||||
|
||||
/// Unified error type for storage, workspace metadata, and sync protocol operations.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum StoreError {
|
||||
#[error("invalid binary CRDT update: {0}")]
|
||||
InvalidBinary(String),
|
||||
|
||||
#[error("invalid protocol payload: {0}")]
|
||||
InvalidProtocol(String),
|
||||
|
||||
#[error("invalid path argument: {0}")]
|
||||
InvalidPath(String),
|
||||
|
||||
#[error("document not found: {0}")]
|
||||
DocNotFound(String),
|
||||
|
||||
#[error("workspace root meta.pages is not initialized")]
|
||||
RootMetaNotInitialized,
|
||||
|
||||
#[error("companion workspace table `{0}` is not resolved; load it or mark it absent first")]
|
||||
DbTableNotResolved(String),
|
||||
|
||||
#[error("concurrent modification prevented write")]
|
||||
ConcurrentModification,
|
||||
|
||||
#[error("operation cancelled")]
|
||||
Cancelled,
|
||||
|
||||
#[error("permission revoked ({code}): {message}")]
|
||||
PermissionRevoked { code: String, message: String },
|
||||
|
||||
#[error("y-octo error: {0}")]
|
||||
YOcto(String),
|
||||
|
||||
#[error("json error: {0}")]
|
||||
Json(#[from] serde_json::Error),
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
#[error("sqlx error: {0}")]
|
||||
Sqlx(#[from] sqlx::Error),
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
#[error("migration error: {0}")]
|
||||
Migrate(#[from] sqlx::migrate::MigrateError),
|
||||
}
|
||||
|
||||
pub type StoreResult<T> = Result<T, StoreError>;
|
||||
@@ -0,0 +1,326 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use y_octo::{
|
||||
Any, DocOptions, DocSession, SessionConfig, SessionReadValue, SessionUndoConfig, TypePath,
|
||||
TypeTarget,
|
||||
};
|
||||
|
||||
use crate::error::{StoreError, StoreResult};
|
||||
|
||||
/// Bidirectional document ID converter matching `packages/common/nbstore/src/utils/id-converter.ts`.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct IdConverter {
|
||||
space_id: String,
|
||||
old_to_new: BTreeMap<String, String>,
|
||||
new_to_old: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl IdConverter {
|
||||
/// Build a converter with no page aliases.
|
||||
pub fn new(space_id: impl Into<String>) -> Self {
|
||||
let space_id = space_id.into();
|
||||
let mut old_to_new = BTreeMap::new();
|
||||
let mut new_to_old = BTreeMap::new();
|
||||
old_to_new.insert(space_id.clone(), space_id.clone());
|
||||
new_to_old.insert(space_id.clone(), space_id.clone());
|
||||
Self {
|
||||
space_id,
|
||||
old_to_new,
|
||||
new_to_old,
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a converter with an explicit legacy root document GUID when `root_doc_id != space_id`.
|
||||
pub fn with_root_doc_id(space_id: impl Into<String>, root_doc_id: impl Into<String>) -> Self {
|
||||
let space_id = space_id.into();
|
||||
let root_doc_id = root_doc_id.into();
|
||||
let mut converter = Self::new(space_id.clone());
|
||||
if root_doc_id != space_id {
|
||||
converter
|
||||
.old_to_new
|
||||
.insert(root_doc_id.clone(), space_id.clone());
|
||||
converter.new_to_old.insert(space_id, root_doc_id);
|
||||
}
|
||||
converter
|
||||
}
|
||||
|
||||
/// Build a converter from explicit bidirectional maps.
|
||||
pub fn from_maps(
|
||||
space_id: impl Into<String>,
|
||||
old_to_new: BTreeMap<String, String>,
|
||||
new_to_old: BTreeMap<String, String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
space_id: space_id.into(),
|
||||
old_to_new,
|
||||
new_to_old,
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract page-to-subdoc GUID aliases from an encoded root YDoc update.
|
||||
pub fn from_root_doc_bytes(
|
||||
space_id: impl Into<String>,
|
||||
root_doc_id: Option<&str>,
|
||||
root_doc_bytes: Option<&[u8]>,
|
||||
) -> StoreResult<Self> {
|
||||
let space_id = space_id.into();
|
||||
let effective_root_id = root_doc_id.unwrap_or(&space_id);
|
||||
let mut converter = Self::with_root_doc_id(space_id.clone(), effective_root_id);
|
||||
|
||||
let Some(bytes) = root_doc_bytes else {
|
||||
return Ok(converter);
|
||||
};
|
||||
if bytes.is_empty() || bytes == [0, 0] {
|
||||
return Ok(converter);
|
||||
}
|
||||
|
||||
let options = DocOptions::from_identity(1, effective_root_id.to_string());
|
||||
let mut session = DocSession::<()>::with_config(
|
||||
options,
|
||||
SessionConfig {
|
||||
undo: SessionUndoConfig::Disabled,
|
||||
},
|
||||
);
|
||||
session
|
||||
.apply_update_v1(bytes)
|
||||
.map_err(|err| StoreError::InvalidBinary(err.to_string()))?;
|
||||
|
||||
let pages_target = TypeTarget::Path(TypePath::root("meta").key("pages"));
|
||||
let Ok(page_items) = session.read_array(&pages_target) else {
|
||||
return Ok(converter);
|
||||
};
|
||||
|
||||
let spaces_target = TypeTarget::Path(TypePath::root("spaces"));
|
||||
for item in page_items {
|
||||
let SessionReadValue::Map(map_id) = item else {
|
||||
continue;
|
||||
};
|
||||
let Ok(Some(SessionReadValue::Any(Any::String(page_id)))) =
|
||||
session.get_map_value(&TypeTarget::Identity(map_id), "id")
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if page_id.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Ok(Some(SessionReadValue::Doc { guid, .. })) =
|
||||
session.get_map_value(&spaces_target, &page_id)
|
||||
{
|
||||
converter.register_page_mapping(page_id, guid);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(converter)
|
||||
}
|
||||
|
||||
/// Register a bidirectional alias between normalized `page_id` and legacy `subdoc_guid`.
|
||||
pub fn register_page_mapping(
|
||||
&mut self,
|
||||
page_id: impl Into<String>,
|
||||
subdoc_guid: impl Into<String>,
|
||||
) {
|
||||
let page_id = page_id.into();
|
||||
let subdoc_guid = subdoc_guid.into();
|
||||
self.old_to_new.insert(subdoc_guid.clone(), page_id.clone());
|
||||
self.new_to_old.insert(page_id, subdoc_guid);
|
||||
}
|
||||
|
||||
/// Return the workspace ID this converter belongs to.
|
||||
pub fn space_id(&self) -> &str {
|
||||
&self.space_id
|
||||
}
|
||||
|
||||
/// Convert a local normalized document ID to the legacy/wire document ID.
|
||||
pub fn new_id_to_old_id(&self, new_id: &str) -> String {
|
||||
if let Some(rest) = new_id.strip_prefix("db$") {
|
||||
return format!("db${}${rest}", self.space_id);
|
||||
}
|
||||
if let Some(converted) = convert_userdata_new_to_old(new_id, &self.space_id) {
|
||||
return converted;
|
||||
}
|
||||
self.new_to_old
|
||||
.get(new_id)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| new_id.to_string())
|
||||
}
|
||||
|
||||
/// Convert a legacy/wire document ID to the local normalized document ID.
|
||||
pub fn old_id_to_new_id(&self, old_id: &str) -> String {
|
||||
let db_prefix = format!("db${}$", self.space_id);
|
||||
if let Some(rest) = old_id.strip_prefix(&db_prefix) {
|
||||
return format!("db${rest}");
|
||||
}
|
||||
if let Some(converted) = convert_userdata_old_to_new(old_id, &self.space_id) {
|
||||
return converted;
|
||||
}
|
||||
self.old_to_new
|
||||
.get(old_id)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| old_id.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn is_word_or_hyphen(byte: u8) -> bool {
|
||||
byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-'
|
||||
}
|
||||
|
||||
/// Mirrors `newId.replace(/^(userdata\$[\w-]+)\$([^\$]+)/, (_, p1, p2) => `${p1}$${spaceId}$${p2}`)`.
|
||||
fn convert_userdata_new_to_old(new_id: &str, space_id: &str) -> Option<String> {
|
||||
let rest = new_id.strip_prefix("userdata$")?;
|
||||
let dollar_pos = rest.find('$')?;
|
||||
let user_id = &rest[..dollar_pos];
|
||||
if user_id.is_empty() || !user_id.bytes().all(is_word_or_hyphen) {
|
||||
return None;
|
||||
}
|
||||
let after_user = &rest[dollar_pos + 1..];
|
||||
if after_user.is_empty() || after_user.starts_with('$') {
|
||||
return None;
|
||||
}
|
||||
Some(format!("userdata${user_id}${space_id}${after_user}"))
|
||||
}
|
||||
|
||||
/// Mirrors `oldId.match(/^userdata\$[\w-]+\$<spaceId>\$/)` then `oldId.replace(`$${spaceId}$`, '$')`.
|
||||
fn convert_userdata_old_to_new(old_id: &str, space_id: &str) -> Option<String> {
|
||||
let rest = old_id.strip_prefix("userdata$")?;
|
||||
let dollar_pos = rest.find('$')?;
|
||||
let user_id = &rest[..dollar_pos];
|
||||
if user_id.is_empty() || !user_id.bytes().all(is_word_or_hyphen) {
|
||||
return None;
|
||||
}
|
||||
let after_user = &rest[dollar_pos + 1..];
|
||||
let space_prefix = format!("{space_id}$");
|
||||
let remainder = after_user.strip_prefix(&space_prefix)?;
|
||||
Some(format!("userdata${user_id}${remainder}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use y_octo::{SessionTxOrigin, SessionValue, YTypeKind};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn table_driven_id_conversion_roundtrips_all_branches() {
|
||||
let mut converter = IdConverter::with_root_doc_id("ws-1", "legacy-root-guid");
|
||||
converter.register_page_mapping("page-a", "subdoc-guid-a");
|
||||
|
||||
let cases = [
|
||||
// Root doc with guid != spaceId
|
||||
("ws-1", "legacy-root-guid"),
|
||||
// Legacy page subdoc GUID mapping
|
||||
("page-a", "subdoc-guid-a"),
|
||||
// Normal page with identical GUID
|
||||
("page-b", "page-b"),
|
||||
// All 5 workspace db$ tables
|
||||
("db$folders", "db$ws-1$folders"),
|
||||
("db$docProperties", "db$ws-1$docProperties"),
|
||||
("db$docCustomPropertyInfo", "db$ws-1$docCustomPropertyInfo"),
|
||||
("db$pinnedCollections", "db$ws-1$pinnedCollections"),
|
||||
("db$explorerIcon", "db$ws-1$explorerIcon"),
|
||||
// All 3 userdata$ tables with user id and __local__
|
||||
(
|
||||
"userdata$user-42$favorite",
|
||||
"userdata$user-42$ws-1$favorite",
|
||||
),
|
||||
(
|
||||
"userdata$user-42$settings",
|
||||
"userdata$user-42$ws-1$settings",
|
||||
),
|
||||
(
|
||||
"userdata$user-42$docIntegrationRef",
|
||||
"userdata$user-42$ws-1$docIntegrationRef",
|
||||
),
|
||||
(
|
||||
"userdata$__local__$favorite",
|
||||
"userdata$__local__$ws-1$favorite",
|
||||
),
|
||||
];
|
||||
|
||||
for (local_id, wire_id) in cases {
|
||||
assert_eq!(
|
||||
converter.new_id_to_old_id(local_id),
|
||||
wire_id,
|
||||
"new->old for {local_id}"
|
||||
);
|
||||
assert_eq!(
|
||||
converter.old_id_to_new_id(wire_id),
|
||||
local_id,
|
||||
"old->new for {wire_id}"
|
||||
);
|
||||
}
|
||||
|
||||
// Foreign space db$ and userdata$ IDs must pass through unchanged.
|
||||
assert_eq!(
|
||||
converter.old_id_to_new_id("db$other-ws$folders"),
|
||||
"db$other-ws$folders"
|
||||
);
|
||||
assert_eq!(
|
||||
converter.old_id_to_new_id("userdata$u1$other-ws$favorite"),
|
||||
"userdata$u1$other-ws$favorite"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_root_doc_bytes_extracts_subdoc_guid_aliases() {
|
||||
let options = DocOptions::from_identity(1, "legacy-root".to_string());
|
||||
let mut session = DocSession::<()>::with_config(
|
||||
options,
|
||||
SessionConfig {
|
||||
undo: SessionUndoConfig::Disabled,
|
||||
},
|
||||
);
|
||||
let meta = TypeTarget::from(session.ensure_root("meta", YTypeKind::Map).unwrap());
|
||||
let spaces = TypeTarget::from(session.ensure_root("spaces", YTypeKind::Map).unwrap());
|
||||
session.begin_tx(SessionTxOrigin::Untracked).unwrap();
|
||||
session
|
||||
.map_set(&meta, "pages".to_string(), SessionValue::Array(Vec::new()))
|
||||
.unwrap();
|
||||
let pages_target = TypeTarget::Path(TypePath::root("meta").key("pages"));
|
||||
session
|
||||
.array_push(
|
||||
&pages_target,
|
||||
vec![
|
||||
SessionValue::Map(vec![(
|
||||
"id".to_string(),
|
||||
SessionValue::Any(Any::String("page-1".to_string())),
|
||||
)]),
|
||||
SessionValue::Map(vec![(
|
||||
"id".to_string(),
|
||||
SessionValue::Any(Any::String("page-2".to_string())),
|
||||
)]),
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
session
|
||||
.map_set(
|
||||
&spaces,
|
||||
"page-1".to_string(),
|
||||
SessionValue::Doc {
|
||||
guid: "old-guid-1".to_string(),
|
||||
gc: true,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
session
|
||||
.map_set(
|
||||
&spaces,
|
||||
"page-2".to_string(),
|
||||
SessionValue::Doc {
|
||||
guid: "page-2".to_string(),
|
||||
gc: true,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let commit = session.commit_tx().unwrap().unwrap();
|
||||
|
||||
let converter =
|
||||
IdConverter::from_root_doc_bytes("space-1", Some("legacy-root"), Some(&commit.update))
|
||||
.unwrap();
|
||||
assert_eq!(converter.new_id_to_old_id("space-1"), "legacy-root");
|
||||
assert_eq!(converter.old_id_to_new_id("legacy-root"), "space-1");
|
||||
assert_eq!(converter.new_id_to_old_id("page-1"), "old-guid-1");
|
||||
assert_eq!(converter.old_id_to_new_id("old-guid-1"), "page-1");
|
||||
assert_eq!(converter.new_id_to_old_id("page-2"), "page-2");
|
||||
assert_eq!(converter.old_id_to_new_id("page-2"), "page-2");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod blob_api;
|
||||
pub mod clock;
|
||||
pub mod directory;
|
||||
pub mod error;
|
||||
pub mod id_converter;
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub mod sqlite;
|
||||
pub mod sync;
|
||||
pub mod workspace_db;
|
||||
|
||||
pub use clock::{Clock, ManualClock};
|
||||
pub use error::{StoreError, StoreResult};
|
||||
pub use id_converter::IdConverter;
|
||||
@@ -0,0 +1,183 @@
|
||||
use chrono::NaiveDateTime;
|
||||
use sqlx::Row;
|
||||
|
||||
use super::{BlobRecord, ListedBlob, SetBlob, SqliteDocStorage, millis_to_naive_utc};
|
||||
use crate::error::StoreResult;
|
||||
|
||||
impl SqliteDocStorage {
|
||||
/// Read a non-deleted blob by key.
|
||||
pub async fn get_blob(&self, key: &str) -> StoreResult<Option<BlobRecord>> {
|
||||
let row = sqlx::query(
|
||||
"SELECT key, data, size, mime, created_at FROM blobs \
|
||||
WHERE key = ? AND deleted_at IS NULL",
|
||||
)
|
||||
.bind(key)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
|
||||
row.map(|r| {
|
||||
Ok(BlobRecord {
|
||||
key: r.try_get("key")?,
|
||||
data: r.try_get("data")?,
|
||||
mime: r.try_get("mime")?,
|
||||
size: r.try_get("size")?,
|
||||
created_at: r.try_get("created_at")?,
|
||||
})
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
/// Insert or replace a blob and clear any previous soft-delete timestamp.
|
||||
pub async fn set_blob(&self, blob: SetBlob) -> StoreResult<()> {
|
||||
sqlx::query(
|
||||
"INSERT INTO blobs (key, data, mime, size) VALUES ($1, $2, $3, $4) \
|
||||
ON CONFLICT(key) DO UPDATE SET data = $2, mime = $3, size = $4, deleted_at = NULL;",
|
||||
)
|
||||
.bind(&blob.key)
|
||||
.bind(&blob.data)
|
||||
.bind(&blob.mime)
|
||||
.bind(blob.data.len() as i64)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Soft-delete or permanently delete a blob using an explicit deterministic timestamp.
|
||||
pub async fn delete_blob(&self, key: &str, permanently: bool, now_ms: i64) -> StoreResult<()> {
|
||||
if permanently {
|
||||
sqlx::query("DELETE FROM blobs WHERE key = ?")
|
||||
.bind(key)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
} else {
|
||||
let deleted_at = millis_to_naive_utc(now_ms);
|
||||
sqlx::query("UPDATE blobs SET deleted_at = ? WHERE key = ?")
|
||||
.bind(deleted_at)
|
||||
.bind(key)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Permanently purge all soft-deleted blobs.
|
||||
pub async fn release_blobs(&self) -> StoreResult<()> {
|
||||
sqlx::query("DELETE FROM blobs WHERE deleted_at IS NOT NULL;")
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// List all non-deleted blobs ordered by `created_at DESC`.
|
||||
pub async fn list_blobs(&self) -> StoreResult<Vec<ListedBlob>> {
|
||||
let rows = sqlx::query(
|
||||
"SELECT key, size, mime, created_at FROM blobs \
|
||||
WHERE deleted_at IS NULL ORDER BY created_at DESC;",
|
||||
)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
|
||||
rows.iter()
|
||||
.map(|r| {
|
||||
Ok(ListedBlob {
|
||||
key: r.try_get("key")?,
|
||||
size: r.try_get("size")?,
|
||||
mime: r.try_get("mime")?,
|
||||
created_at: r.try_get("created_at")?,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Record or clear the `uploaded_at` timestamp for `(peer, blob_id)` in `peer_blob_sync`.
|
||||
pub async fn set_blob_uploaded_at(
|
||||
&self,
|
||||
peer: &str,
|
||||
blob_id: &str,
|
||||
uploaded_at: Option<NaiveDateTime>,
|
||||
) -> StoreResult<()> {
|
||||
sqlx::query(
|
||||
"INSERT INTO peer_blob_sync (peer, blob_id, uploaded_at) VALUES ($1, $2, $3) \
|
||||
ON CONFLICT(peer, blob_id) DO UPDATE SET uploaded_at = $3;",
|
||||
)
|
||||
.bind(peer)
|
||||
.bind(blob_id)
|
||||
.bind(uploaded_at)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read the `uploaded_at` timestamp for `(peer, blob_id)` from `peer_blob_sync`.
|
||||
pub async fn get_blob_uploaded_at(
|
||||
&self,
|
||||
peer: &str,
|
||||
blob_id: &str,
|
||||
) -> StoreResult<Option<NaiveDateTime>> {
|
||||
let row =
|
||||
sqlx::query("SELECT uploaded_at FROM peer_blob_sync WHERE peer = ? AND blob_id = ?")
|
||||
.bind(peer)
|
||||
.bind(blob_id)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
|
||||
match row {
|
||||
Some(r) => Ok(r.try_get("uploaded_at")?),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn blob_crud_soft_delete_release_and_peer_sync_clock() {
|
||||
let storage = SqliteDocStorage::new(":memory:");
|
||||
storage.connect().await.unwrap();
|
||||
|
||||
storage
|
||||
.set_blob(SetBlob {
|
||||
key: "k1".into(),
|
||||
data: vec![10, 20, 30],
|
||||
mime: "image/png".into(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
storage
|
||||
.set_blob(SetBlob {
|
||||
key: "k2".into(),
|
||||
data: vec![40, 50],
|
||||
mime: "text/plain".into(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(storage.list_blobs().await.unwrap().len(), 2);
|
||||
storage.delete_blob("k1", false, 1_000).await.unwrap();
|
||||
assert!(storage.get_blob("k1").await.unwrap().is_none());
|
||||
assert_eq!(storage.list_blobs().await.unwrap().len(), 1);
|
||||
storage.release_blobs().await.unwrap();
|
||||
|
||||
let ts = millis_to_naive_utc(5_000);
|
||||
storage
|
||||
.set_blob_uploaded_at("cloud", "k2", Some(ts))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
storage.get_blob_uploaded_at("cloud", "k2").await.unwrap(),
|
||||
Some(ts)
|
||||
);
|
||||
storage
|
||||
.set_blob_uploaded_at("cloud", "k2", None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
storage.get_blob_uploaded_at("cloud", "k2").await.unwrap(),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,648 @@
|
||||
use chrono::NaiveDateTime;
|
||||
use sqlx::{QueryBuilder, Row};
|
||||
use y_octo::{
|
||||
diff_update_v1, encode_state_vector_from_update_v1, merge_updates_v1, validate_update_v1,
|
||||
};
|
||||
|
||||
use super::{DocClock, DocDiff, DocRecord, DocUpdate, SqliteDocStorage, millis_to_naive_utc};
|
||||
use crate::error::{StoreError, StoreResult};
|
||||
|
||||
fn is_empty_update(bin: &[u8]) -> bool {
|
||||
bin.is_empty() || bin == [0, 0]
|
||||
}
|
||||
|
||||
/// Merge a slice of encoded v1 CRDT updates into a single v1 update.
|
||||
pub fn merge_updates(updates: &[&[u8]]) -> StoreResult<Vec<u8>> {
|
||||
let non_empty: Vec<&[u8]> = updates
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|u| !is_empty_update(u))
|
||||
.collect();
|
||||
match non_empty.as_slice() {
|
||||
[] => Ok(vec![0, 0]),
|
||||
[single] => {
|
||||
validate_update_v1(single).map_err(|err| StoreError::InvalidBinary(err.to_string()))?;
|
||||
Ok((*single).to_vec())
|
||||
}
|
||||
many => merge_updates_v1(many.iter().copied())
|
||||
.and_then(|merged| merged.encode_v1())
|
||||
.map_err(|err| StoreError::InvalidBinary(err.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
fn row_to_doc_record(row: &sqlx::sqlite::SqliteRow) -> StoreResult<DocRecord> {
|
||||
Ok(DocRecord {
|
||||
doc_id: row.try_get("doc_id")?,
|
||||
bin: row.try_get("bin")?,
|
||||
timestamp: row.try_get("timestamp")?,
|
||||
})
|
||||
}
|
||||
|
||||
fn row_to_doc_update(row: &sqlx::sqlite::SqliteRow) -> StoreResult<DocUpdate> {
|
||||
Ok(DocUpdate {
|
||||
doc_id: row.try_get("doc_id")?,
|
||||
timestamp: row.try_get("timestamp")?,
|
||||
bin: row.try_get("bin")?,
|
||||
})
|
||||
}
|
||||
|
||||
impl SqliteDocStorage {
|
||||
/// Set or rename the workspace `space_id` in `meta`, migrating root doc rows if renamed.
|
||||
pub async fn set_space_id(&self, space_id: &str) -> StoreResult<()> {
|
||||
let existing = sqlx::query("SELECT space_id FROM meta LIMIT 1;")
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
|
||||
match existing {
|
||||
Some(row) => {
|
||||
let current_id: String = row.try_get("space_id")?;
|
||||
if current_id != space_id {
|
||||
let mut tx = self.pool.begin().await?;
|
||||
sqlx::query("UPDATE meta SET space_id = $1;")
|
||||
.bind(space_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
for table in [
|
||||
"updates",
|
||||
"snapshots",
|
||||
"clocks",
|
||||
"indexer_sync",
|
||||
"peer_clocks",
|
||||
] {
|
||||
let sql = format!("UPDATE {table} SET doc_id = $1 WHERE doc_id = $2;");
|
||||
sqlx::query(&sql)
|
||||
.bind(space_id)
|
||||
.bind(¤t_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
sqlx::query("INSERT INTO meta (space_id) VALUES ($1);")
|
||||
.bind(space_id)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Push a document update using an explicit deterministic timestamp in milliseconds.
|
||||
pub async fn push_update<U: AsRef<[u8]>>(
|
||||
&self,
|
||||
doc_id: &str,
|
||||
update: U,
|
||||
now_ms: i64,
|
||||
) -> StoreResult<NaiveDateTime> {
|
||||
self.push_update_with_peer(doc_id, update, None, now_ms)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Push a document update, optionally marking `pending_create` for `create_for_peer`.
|
||||
pub async fn push_update_with_peer<U: AsRef<[u8]>>(
|
||||
&self,
|
||||
doc_id: &str,
|
||||
update: U,
|
||||
create_for_peer: Option<&str>,
|
||||
now_ms: i64,
|
||||
) -> StoreResult<NaiveDateTime> {
|
||||
let mut timestamp = millis_to_naive_utc(now_ms);
|
||||
|
||||
for attempt in 0..12 {
|
||||
match self
|
||||
.try_insert_update_with_timestamp(
|
||||
doc_id,
|
||||
update.as_ref(),
|
||||
timestamp,
|
||||
create_for_peer,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(true) => return Ok(timestamp),
|
||||
Ok(false) => {}
|
||||
Err(err) if attempt == 11 => return Err(err.into()),
|
||||
Err(_) => {}
|
||||
}
|
||||
let clock = self.get_doc_clock(doc_id).await?.map(|c| c.timestamp);
|
||||
timestamp = (timestamp + chrono::Duration::milliseconds(1)).max(
|
||||
clock
|
||||
.map(|c| c + chrono::Duration::milliseconds(1))
|
||||
.unwrap_or(timestamp),
|
||||
);
|
||||
}
|
||||
|
||||
Err(StoreError::ConcurrentModification)
|
||||
}
|
||||
|
||||
/// Atomically persist a batch of [`crate::workspace_db::PendingDocUpdate`] entries inside a
|
||||
/// single `BEGIN IMMEDIATE` SQLite transaction.
|
||||
///
|
||||
/// Guarantees multi-document logical mutations (such as root `meta.pages` + `db$docProperties`
|
||||
/// during Edgeless document creation) commit all-or-nothing on disk without WAL read-to-write
|
||||
/// snapshot upgrade failures (`SQLITE_BUSY_SNAPSHOT`). Pass `create_for_peer = None` when
|
||||
/// persisting root/`db$` metadata updates for an already-created workspace; `Some(peer)` marks
|
||||
/// every document in `updates` with `pending_create = TRUE` for `peer`.
|
||||
pub async fn push_updates_batch(
|
||||
&self,
|
||||
updates: &[crate::workspace_db::PendingDocUpdate],
|
||||
create_for_peer: Option<&str>,
|
||||
now_ms: i64,
|
||||
) -> StoreResult<Vec<(String, NaiveDateTime)>> {
|
||||
let non_empty: Vec<&crate::workspace_db::PendingDocUpdate> = updates
|
||||
.iter()
|
||||
.filter(|u| !is_empty_update(&u.update))
|
||||
.collect();
|
||||
if non_empty.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let base_ts = millis_to_naive_utc(now_ms);
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
let mut committed = Vec::with_capacity(non_empty.len());
|
||||
|
||||
for item in non_empty {
|
||||
let existing_clock: Option<NaiveDateTime> =
|
||||
sqlx::query("SELECT timestamp FROM clocks WHERE doc_id = $1")
|
||||
.bind(&item.doc_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
.map(|row| row.try_get("timestamp"))
|
||||
.transpose()?;
|
||||
let effective_ts = match existing_clock {
|
||||
Some(clock_ts) if clock_ts >= base_ts => {
|
||||
clock_ts + chrono::Duration::milliseconds(1)
|
||||
}
|
||||
_ => base_ts,
|
||||
};
|
||||
|
||||
sqlx::query("INSERT INTO updates (doc_id, data, created_at) VALUES ($1, $2, $3)")
|
||||
.bind(&item.doc_id)
|
||||
.bind(&item.update)
|
||||
.bind(effective_ts)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
sqlx::query(
|
||||
"INSERT INTO clocks (doc_id, timestamp) VALUES ($1, $2) \
|
||||
ON CONFLICT(doc_id) DO UPDATE SET timestamp = MAX(clocks.timestamp, excluded.timestamp);",
|
||||
)
|
||||
.bind(&item.doc_id)
|
||||
.bind(effective_ts)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
if let Some(peer) = create_for_peer {
|
||||
sqlx::query(
|
||||
"INSERT INTO peer_clocks (peer, doc_id, pending_create) VALUES ($1, $2, TRUE) \
|
||||
ON CONFLICT(peer, doc_id) DO UPDATE SET pending_create = TRUE",
|
||||
)
|
||||
.bind(peer)
|
||||
.bind(&item.doc_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO peer_clocks (peer, doc_id, cache_token) \
|
||||
SELECT $1, space_id, 1 FROM meta WHERE TRUE \
|
||||
ON CONFLICT(peer, doc_id) DO UPDATE SET cache_token = cache_token + 1",
|
||||
)
|
||||
.bind(peer)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
|
||||
committed.push((item.doc_id.clone(), effective_ts));
|
||||
}
|
||||
|
||||
tx.commit().await?;
|
||||
Ok(committed)
|
||||
}
|
||||
|
||||
async fn try_insert_update_with_timestamp(
|
||||
&self,
|
||||
doc_id: &str,
|
||||
update: &[u8],
|
||||
timestamp: NaiveDateTime,
|
||||
create_for_peer: Option<&str>,
|
||||
) -> sqlx::Result<bool> {
|
||||
let mut tx = self.pool.begin().await?;
|
||||
|
||||
let inserted = sqlx::query(
|
||||
"INSERT INTO updates (doc_id, data, created_at) \
|
||||
SELECT $1, $2, $3 WHERE NOT EXISTS (\
|
||||
SELECT 1 FROM clocks WHERE doc_id = $1 AND timestamp >= $3\
|
||||
)",
|
||||
)
|
||||
.bind(doc_id)
|
||||
.bind(update)
|
||||
.bind(timestamp)
|
||||
.execute(&mut *tx)
|
||||
.await?
|
||||
.rows_affected();
|
||||
if inserted == 0 {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
sqlx::query(
|
||||
"INSERT INTO clocks (doc_id, timestamp) VALUES ($1, $2) \
|
||||
ON CONFLICT(doc_id) DO UPDATE SET timestamp = MAX(clocks.timestamp, excluded.timestamp);",
|
||||
)
|
||||
.bind(doc_id)
|
||||
.bind(timestamp)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
if let Some(peer) = create_for_peer {
|
||||
sqlx::query(
|
||||
"INSERT INTO peer_clocks (peer, doc_id, pending_create) VALUES ($1, $2, TRUE) \
|
||||
ON CONFLICT(peer, doc_id) DO UPDATE SET pending_create = TRUE",
|
||||
)
|
||||
.bind(peer)
|
||||
.bind(doc_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO peer_clocks (peer, doc_id, cache_token) \
|
||||
SELECT $1, space_id, 1 FROM meta WHERE TRUE \
|
||||
ON CONFLICT(peer, doc_id) DO UPDATE SET cache_token = cache_token + 1",
|
||||
)
|
||||
.bind(peer)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
|
||||
tx.commit().await?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Read the stored snapshot row for `doc_id` without compacting pending updates.
|
||||
pub async fn get_doc_snapshot(&self, doc_id: &str) -> StoreResult<Option<DocRecord>> {
|
||||
let row = sqlx::query(
|
||||
"SELECT doc_id, data AS bin, updated_at AS timestamp FROM snapshots WHERE doc_id = ?",
|
||||
)
|
||||
.bind(doc_id)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
|
||||
row.as_ref().map(row_to_doc_record).transpose()
|
||||
}
|
||||
|
||||
/// Read and atomically compact `snapshots` + `updates` for `doc_id`.
|
||||
pub async fn get_doc(&self, doc_id: &str) -> StoreResult<Option<DocRecord>> {
|
||||
for _ in 0..8 {
|
||||
let mut read_tx = self.pool.begin().await?;
|
||||
let snapshot_row = sqlx::query(
|
||||
"SELECT doc_id, data AS bin, updated_at AS timestamp FROM snapshots WHERE doc_id = ?",
|
||||
)
|
||||
.bind(doc_id)
|
||||
.fetch_optional(&mut *read_tx)
|
||||
.await?;
|
||||
let snapshot = snapshot_row.as_ref().map(row_to_doc_record).transpose()?;
|
||||
|
||||
let update_rows = sqlx::query(
|
||||
"SELECT doc_id, created_at AS timestamp, data AS bin \
|
||||
FROM updates WHERE doc_id = ? ORDER BY created_at",
|
||||
)
|
||||
.bind(doc_id)
|
||||
.fetch_all(&mut *read_tx)
|
||||
.await?;
|
||||
let updates: Vec<DocUpdate> = update_rows
|
||||
.iter()
|
||||
.map(row_to_doc_update)
|
||||
.collect::<StoreResult<_>>()?;
|
||||
read_tx.commit().await?;
|
||||
|
||||
if updates.is_empty() {
|
||||
return Ok(snapshot);
|
||||
}
|
||||
|
||||
let timestamp = updates
|
||||
.last()
|
||||
.map(|u| u.timestamp)
|
||||
.into_iter()
|
||||
.chain(snapshot.as_ref().map(|r| r.timestamp))
|
||||
.max()
|
||||
.ok_or(StoreError::ConcurrentModification)?;
|
||||
|
||||
let mut segments = Vec::with_capacity(updates.len() + usize::from(snapshot.is_some()));
|
||||
if let Some(record) = &snapshot {
|
||||
segments.push(record.bin.as_slice());
|
||||
}
|
||||
for update in &updates {
|
||||
segments.push(update.bin.as_slice());
|
||||
}
|
||||
let bin = merge_updates(&segments)?;
|
||||
|
||||
let mut tx = self.pool.begin().await?;
|
||||
let installed = if let Some(previous) = &snapshot {
|
||||
sqlx::query(
|
||||
"UPDATE snapshots SET data = ?, updated_at = ? \
|
||||
WHERE doc_id = ? AND updated_at = ? AND data = ?",
|
||||
)
|
||||
.bind(&bin)
|
||||
.bind(timestamp)
|
||||
.bind(doc_id)
|
||||
.bind(previous.timestamp)
|
||||
.bind(&previous.bin)
|
||||
.execute(&mut *tx)
|
||||
.await?
|
||||
.rows_affected()
|
||||
} else {
|
||||
sqlx::query(
|
||||
"INSERT INTO snapshots (doc_id, data, updated_at) VALUES (?, ?, ?) \
|
||||
ON CONFLICT DO NOTHING",
|
||||
)
|
||||
.bind(doc_id)
|
||||
.bind(&bin)
|
||||
.bind(timestamp)
|
||||
.execute(&mut *tx)
|
||||
.await?
|
||||
.rows_affected()
|
||||
};
|
||||
if installed != 1 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let current_rows = sqlx::query(
|
||||
"SELECT doc_id, created_at AS timestamp, data AS bin \
|
||||
FROM updates WHERE doc_id = ? ORDER BY created_at",
|
||||
)
|
||||
.bind(doc_id)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?;
|
||||
let current_updates: Vec<DocUpdate> = current_rows
|
||||
.iter()
|
||||
.map(row_to_doc_update)
|
||||
.collect::<StoreResult<_>>()?;
|
||||
|
||||
if current_updates != updates {
|
||||
continue;
|
||||
}
|
||||
|
||||
sqlx::query("DELETE FROM updates WHERE doc_id = ?")
|
||||
.bind(doc_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
|
||||
return Ok(Some(DocRecord {
|
||||
doc_id: doc_id.to_string(),
|
||||
bin,
|
||||
timestamp,
|
||||
}));
|
||||
}
|
||||
|
||||
Err(StoreError::ConcurrentModification)
|
||||
}
|
||||
|
||||
/// Compute the merged diff and state vector against an optional `remote_state_vector`.
|
||||
pub async fn get_doc_diff(
|
||||
&self,
|
||||
doc_id: &str,
|
||||
remote_state_vector: Option<&[u8]>,
|
||||
) -> StoreResult<Option<DocDiff>> {
|
||||
let mut read_tx = self.pool.begin().await?;
|
||||
let snapshot_row = sqlx::query(
|
||||
"SELECT doc_id, data AS bin, updated_at AS timestamp FROM snapshots WHERE doc_id = ?",
|
||||
)
|
||||
.bind(doc_id)
|
||||
.fetch_optional(&mut *read_tx)
|
||||
.await?;
|
||||
let snapshot = snapshot_row.as_ref().map(row_to_doc_record).transpose()?;
|
||||
|
||||
let update_rows = sqlx::query(
|
||||
"SELECT doc_id, created_at AS timestamp, data AS bin \
|
||||
FROM updates WHERE doc_id = ? ORDER BY created_at",
|
||||
)
|
||||
.bind(doc_id)
|
||||
.fetch_all(&mut *read_tx)
|
||||
.await?;
|
||||
let updates: Vec<DocUpdate> = update_rows
|
||||
.iter()
|
||||
.map(row_to_doc_update)
|
||||
.collect::<StoreResult<_>>()?;
|
||||
read_tx.commit().await?;
|
||||
|
||||
if snapshot.is_none() && updates.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let timestamp = updates
|
||||
.last()
|
||||
.map(|u| u.timestamp)
|
||||
.into_iter()
|
||||
.chain(snapshot.as_ref().map(|r| r.timestamp))
|
||||
.max()
|
||||
.ok_or(StoreError::ConcurrentModification)?;
|
||||
|
||||
let merged_bin = if updates.is_empty() {
|
||||
snapshot.map(|s| s.bin).unwrap_or_default()
|
||||
} else {
|
||||
let mut segments = Vec::with_capacity(updates.len() + usize::from(snapshot.is_some()));
|
||||
if let Some(record) = &snapshot {
|
||||
segments.push(record.bin.as_slice());
|
||||
}
|
||||
for update in &updates {
|
||||
segments.push(update.bin.as_slice());
|
||||
}
|
||||
merge_updates(&segments)?
|
||||
};
|
||||
|
||||
let state = encode_state_vector_from_update_v1(&merged_bin)
|
||||
.map_err(|err| StoreError::InvalidBinary(err.to_string()))?;
|
||||
let missing = match remote_state_vector {
|
||||
Some(sv) if !sv.is_empty() => diff_update_v1(&merged_bin, sv)
|
||||
.map_err(|err| StoreError::InvalidBinary(err.to_string()))?,
|
||||
_ => merged_bin,
|
||||
};
|
||||
|
||||
Ok(Some(DocDiff {
|
||||
doc_id: doc_id.to_string(),
|
||||
missing,
|
||||
state,
|
||||
timestamp,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Upsert a document snapshot if its timestamp is at least as new as the stored row.
|
||||
pub async fn set_doc_snapshot(&self, snapshot: &DocRecord) -> StoreResult<bool> {
|
||||
let result = sqlx::query(
|
||||
"INSERT INTO snapshots (doc_id, data, updated_at) VALUES ($1, $2, $3) \
|
||||
ON CONFLICT(doc_id) DO UPDATE SET data = $2, updated_at = $3 \
|
||||
WHERE updated_at <= $3;",
|
||||
)
|
||||
.bind(&snapshot.doc_id)
|
||||
.bind(&snapshot.bin)
|
||||
.bind(snapshot.timestamp)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
|
||||
Ok(result.rows_affected() == 1)
|
||||
}
|
||||
|
||||
/// Fetch all pending updates for `doc_id` ordered by `created_at`.
|
||||
pub async fn get_doc_updates(&self, doc_id: &str) -> StoreResult<Vec<DocUpdate>> {
|
||||
let rows = sqlx::query(
|
||||
"SELECT doc_id, created_at AS timestamp, data AS bin \
|
||||
FROM updates WHERE doc_id = ? ORDER BY created_at",
|
||||
)
|
||||
.bind(doc_id)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
|
||||
rows.iter().map(row_to_doc_update).collect()
|
||||
}
|
||||
|
||||
/// Delete updates whose `created_at` timestamps have been merged into a snapshot.
|
||||
pub async fn mark_updates_merged(
|
||||
&self,
|
||||
doc_id: &str,
|
||||
timestamps: &[NaiveDateTime],
|
||||
) -> StoreResult<u32> {
|
||||
if timestamps.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
let mut qb = QueryBuilder::new("DELETE FROM updates WHERE doc_id = ");
|
||||
qb.push_bind(doc_id);
|
||||
qb.push(" AND created_at IN (");
|
||||
let mut separated = qb.separated(", ");
|
||||
for ts in timestamps {
|
||||
separated.push_bind(*ts);
|
||||
}
|
||||
qb.push(");");
|
||||
|
||||
let result = qb.build().execute(&self.pool).await?;
|
||||
Ok(result.rows_affected() as u32)
|
||||
}
|
||||
|
||||
/// Delete a document across `updates`, `snapshots`, `clocks`, `indexer_sync`,
|
||||
/// and clear any `pending_create` flags in `peer_clocks`.
|
||||
pub async fn delete_doc(&self, doc_id: &str) -> StoreResult<()> {
|
||||
let mut tx = self.pool.begin().await?;
|
||||
for table in ["updates", "snapshots", "clocks", "indexer_sync"] {
|
||||
let sql = format!("DELETE FROM {table} WHERE doc_id = ?;");
|
||||
sqlx::query(&sql).bind(doc_id).execute(&mut *tx).await?;
|
||||
}
|
||||
sqlx::query(
|
||||
"INSERT INTO peer_clocks (peer, doc_id, cache_token) \
|
||||
SELECT peer, meta.space_id, 1 FROM peer_clocks CROSS JOIN meta \
|
||||
WHERE doc_id = $1 AND pending_create = TRUE \
|
||||
ON CONFLICT(peer, doc_id) DO UPDATE SET cache_token = cache_token + 1",
|
||||
)
|
||||
.bind(doc_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"UPDATE peer_clocks SET pending_create = FALSE \
|
||||
WHERE doc_id = $1 AND pending_create = TRUE",
|
||||
)
|
||||
.bind(doc_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Fetch all document clocks, optionally filtered to those strictly after `after`.
|
||||
pub async fn get_doc_clocks(&self, after: Option<NaiveDateTime>) -> StoreResult<Vec<DocClock>> {
|
||||
let rows = if let Some(after_ts) = after {
|
||||
sqlx::query("SELECT doc_id, timestamp FROM clocks WHERE timestamp > $1")
|
||||
.bind(after_ts)
|
||||
.fetch_all(&self.pool)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query("SELECT doc_id, timestamp FROM clocks")
|
||||
.fetch_all(&self.pool)
|
||||
.await?
|
||||
};
|
||||
|
||||
rows.iter()
|
||||
.map(|row| {
|
||||
Ok(DocClock {
|
||||
doc_id: row.try_get("doc_id")?,
|
||||
timestamp: row.try_get("timestamp")?,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Fetch the clock row for a single document.
|
||||
pub async fn get_doc_clock(&self, doc_id: &str) -> StoreResult<Option<DocClock>> {
|
||||
let row = sqlx::query("SELECT doc_id, timestamp FROM clocks WHERE doc_id = ?")
|
||||
.bind(doc_id)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
|
||||
row.map(|r| {
|
||||
Ok(DocClock {
|
||||
doc_id: r.try_get("doc_id")?,
|
||||
timestamp: r.try_get("timestamp")?,
|
||||
})
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use y_octo::DocOptions;
|
||||
|
||||
use super::*;
|
||||
|
||||
async fn open_memory() -> SqliteDocStorage {
|
||||
let storage = SqliteDocStorage::new(":memory:");
|
||||
storage.connect().await.unwrap();
|
||||
storage
|
||||
}
|
||||
|
||||
fn make_text_updates() -> (Vec<u8>, Vec<u8>) {
|
||||
let doc = DocOptions::from_identity(1, "doc".into()).build();
|
||||
let mut text = doc.get_or_create_text("content").unwrap();
|
||||
text.insert(0, "hello").unwrap();
|
||||
let first = doc.encode_update_v1().unwrap();
|
||||
let sv = doc.get_state_vector();
|
||||
text.insert(5, " world").unwrap();
|
||||
let second = doc.encode_state_as_update_v1(&sv).unwrap();
|
||||
(first, second)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn doc_lifecycle_compaction_diff_and_delete() {
|
||||
let storage = open_memory().await;
|
||||
storage.set_space_id("ws-1").await.unwrap();
|
||||
|
||||
let (first, second) = make_text_updates();
|
||||
let t1 = storage.push_update("doc-1", &first, 10_000).await.unwrap();
|
||||
let t2 = storage.push_update("doc-1", &second, 10_000).await.unwrap();
|
||||
assert!(t2 > t1);
|
||||
|
||||
let updates = storage.get_doc_updates("doc-1").await.unwrap();
|
||||
assert_eq!(updates.len(), 2);
|
||||
|
||||
let diff = storage.get_doc_diff("doc-1", None).await.unwrap().unwrap();
|
||||
assert!(!diff.state.is_empty());
|
||||
|
||||
let compacted = storage.get_doc("doc-1").await.unwrap().unwrap();
|
||||
assert_eq!(compacted.timestamp, t2);
|
||||
assert!(storage.get_doc_updates("doc-1").await.unwrap().is_empty());
|
||||
|
||||
let mut verify = DocOptions::from_identity(2, "doc-1".into()).build();
|
||||
verify.apply_update_from_binary_v1(&compacted.bin).unwrap();
|
||||
assert_eq!(
|
||||
verify.get_or_create_text("content").unwrap().to_string(),
|
||||
"hello world"
|
||||
);
|
||||
|
||||
let t3 = storage
|
||||
.push_update("doc-1", [0u8, 0u8], 20_000)
|
||||
.await
|
||||
.unwrap();
|
||||
let removed = storage.mark_updates_merged("doc-1", &[t3]).await.unwrap();
|
||||
assert_eq!(removed, 1);
|
||||
|
||||
storage.delete_doc("doc-1").await.unwrap();
|
||||
assert!(storage.get_doc("doc-1").await.unwrap().is_none());
|
||||
assert!(storage.get_doc_clock("doc-1").await.unwrap().is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
use std::borrow::Cow;
|
||||
|
||||
use sqlx::{
|
||||
Pool, Row,
|
||||
migrate::{Migration, MigrationType, Migrator},
|
||||
sqlite::Sqlite,
|
||||
};
|
||||
|
||||
use crate::error::StoreResult;
|
||||
|
||||
/// Frozen SQLite workspace schema version for 0.27.5 in-place compatibility.
|
||||
pub const FROZEN_SCHEMA_VERSION: i64 = 5;
|
||||
|
||||
pub type SimpleMigration = (&'static str, &'static str, Option<&'static str>);
|
||||
|
||||
// ORDER MATTERS: byte-for-byte identical to `packages/frontend/native/schema/src/lib.rs`.
|
||||
pub const MIGRATIONS: &[SimpleMigration] = &[
|
||||
// v2 db init
|
||||
(
|
||||
"init_v2",
|
||||
r#"
|
||||
CREATE TABLE "meta" (
|
||||
space_id VARCHAR PRIMARY KEY NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE "snapshots" (
|
||||
doc_id VARCHAR PRIMARY KEY NOT NULL,
|
||||
data BLOB NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
updated_at TIMESTAMP NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE "updates" (
|
||||
doc_id VARCHAR NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
data BLOB NOT NULL,
|
||||
PRIMARY KEY (doc_id, created_at)
|
||||
);
|
||||
|
||||
CREATE TABLE "clocks" (
|
||||
doc_id VARCHAR PRIMARY KEY NOT NULL,
|
||||
timestamp TIMESTAMP NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE "blobs" (
|
||||
key VARCHAR PRIMARY KEY NOT NULL,
|
||||
data BLOB NOT NULL,
|
||||
mime VARCHAR NOT NULL,
|
||||
size INTEGER NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
deleted_at TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE "peer_clocks" (
|
||||
peer VARCHAR NOT NULL,
|
||||
doc_id VARCHAR NOT NULL,
|
||||
remote_clock TIMESTAMP NOT NULL DEFAULT 0,
|
||||
pulled_remote_clock TIMESTAMP NOT NULL DEFAULT 0,
|
||||
pushed_clock TIMESTAMP NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (peer, doc_id)
|
||||
);
|
||||
CREATE INDEX peer_clocks_doc_id ON peer_clocks (doc_id);
|
||||
"#,
|
||||
None,
|
||||
),
|
||||
// add blob_sync table
|
||||
(
|
||||
"add_blob_sync",
|
||||
r#"
|
||||
CREATE TABLE "peer_blob_sync" (
|
||||
peer VARCHAR NOT NULL,
|
||||
blob_id VARCHAR NOT NULL,
|
||||
uploaded_at TIMESTAMP,
|
||||
PRIMARY KEY (peer, blob_id)
|
||||
);
|
||||
CREATE INDEX peer_blob_sync_peer ON peer_blob_sync (peer);
|
||||
"#,
|
||||
None,
|
||||
),
|
||||
// add idx snapshots
|
||||
(
|
||||
"add_idx_snapshots",
|
||||
r#"
|
||||
CREATE TABLE idx_snapshots (
|
||||
index_name TEXT PRIMARY KEY NOT NULL,
|
||||
data BLOB NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
"#,
|
||||
None,
|
||||
),
|
||||
// add indexer sync table
|
||||
(
|
||||
"add_indexer_sync",
|
||||
r#"
|
||||
CREATE TABLE "indexer_sync" (
|
||||
doc_id VARCHAR PRIMARY KEY NOT NULL,
|
||||
indexed_clock TIMESTAMP NOT NULL DEFAULT 0,
|
||||
indexer_version INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
"#,
|
||||
None,
|
||||
),
|
||||
(
|
||||
"workspace_inventory",
|
||||
r#"
|
||||
ALTER TABLE peer_clocks ADD COLUMN inventory_kind TEXT;
|
||||
ALTER TABLE peer_clocks ADD COLUMN lifecycle TEXT;
|
||||
ALTER TABLE peer_clocks ADD COLUMN lifecycle_changed_at INTEGER;
|
||||
ALTER TABLE peer_clocks ADD COLUMN pending_create BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
ALTER TABLE peer_clocks ADD COLUMN inventory_ready BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
ALTER TABLE peer_clocks ADD COLUMN cache_token INTEGER NOT NULL DEFAULT 0;
|
||||
"#,
|
||||
None,
|
||||
),
|
||||
];
|
||||
|
||||
/// Build the frozen 5-step `sqlx::migrate::Migrator`.
|
||||
pub fn get_migrator() -> Migrator {
|
||||
let mut migrations = Vec::with_capacity(MIGRATIONS.len());
|
||||
|
||||
for &(name, up, down) in MIGRATIONS {
|
||||
migrations.push(Migration::new(
|
||||
migrations.len() as i64 + 1,
|
||||
Cow::from(name),
|
||||
if down.is_some() {
|
||||
MigrationType::ReversibleUp
|
||||
} else {
|
||||
MigrationType::Simple
|
||||
},
|
||||
Cow::from(up),
|
||||
false,
|
||||
));
|
||||
|
||||
if let Some(down_sql) = down {
|
||||
migrations.push(Migration::new(
|
||||
migrations.len() as i64 + 1,
|
||||
Cow::from(name),
|
||||
MigrationType::ReversibleDown,
|
||||
Cow::from(down_sql),
|
||||
false,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Migrator {
|
||||
migrations: Cow::Owned(migrations),
|
||||
..Migrator::DEFAULT
|
||||
}
|
||||
}
|
||||
|
||||
/// Repair the historical migration #3 (`add_idx_snapshots`) trailing-space SHA-384 checksum
|
||||
/// mismatch from 0.27.4 databases.
|
||||
pub async fn try_repair_migration_3_checksum(
|
||||
pool: &Pool<Sqlite>,
|
||||
migrator: &Migrator,
|
||||
) -> StoreResult<bool> {
|
||||
let Some(migration) = migrator.iter().find(|m| m.version == 3) else {
|
||||
return Ok(false);
|
||||
};
|
||||
|
||||
if migration.description.as_ref() != "add_idx_snapshots" {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let row = sqlx::query("SELECT description, checksum FROM _sqlx_migrations WHERE version = 3")
|
||||
.fetch_optional(pool)
|
||||
.await?;
|
||||
|
||||
let Some(row) = row else {
|
||||
return Ok(false);
|
||||
};
|
||||
|
||||
let applied_description: String = row.try_get("description")?;
|
||||
if applied_description != migration.description.as_ref() {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let applied_checksum: Vec<u8> = row.try_get("checksum")?;
|
||||
let expected_checksum = migration.checksum.as_ref();
|
||||
|
||||
let legacy_sql = format!("{} ", migration.sql);
|
||||
let legacy_migration = Migration::new(
|
||||
migration.version,
|
||||
migration.description.clone(),
|
||||
migration.migration_type,
|
||||
Cow::Owned(legacy_sql),
|
||||
migration.no_tx,
|
||||
);
|
||||
|
||||
if applied_checksum.as_slice() != legacy_migration.checksum.as_ref() {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
sqlx::query("UPDATE _sqlx_migrations SET checksum = ? WHERE version = 3")
|
||||
.bind(expected_checksum)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::path::PathBuf;
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn extract_schema_migrations(source: &str) -> Vec<(String, String)> {
|
||||
let mut out = Vec::new();
|
||||
let mut cursor = source;
|
||||
let marker = "const MIGRATIONS: &[SimpleMigration] = &[";
|
||||
let start = cursor
|
||||
.find(marker)
|
||||
.expect("MIGRATIONS array must exist in affine_schema");
|
||||
cursor = &cursor[start + marker.len()..];
|
||||
|
||||
while let Some(raw_start) = cursor.find("r#\"") {
|
||||
let prefix = &cursor[..raw_start];
|
||||
let name = prefix
|
||||
.rsplit('"')
|
||||
.nth(1)
|
||||
.expect("migration name string before raw SQL")
|
||||
.to_string();
|
||||
let after_open = &cursor[raw_start + 3..];
|
||||
let raw_end = after_open
|
||||
.find("\"#")
|
||||
.expect("closing raw string delimiter");
|
||||
let sql = after_open[..raw_end].to_string();
|
||||
out.push((name, sql));
|
||||
cursor = &after_open[raw_end + 2..];
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn five_migrations_match_native_schema_sha256_byte_for_byte() {
|
||||
let schema_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../frontend/native/schema/src/lib.rs");
|
||||
let schema_source = std::fs::read_to_string(&schema_path)
|
||||
.expect("packages/frontend/native/schema/src/lib.rs must be readable");
|
||||
|
||||
let upstream = extract_schema_migrations(&schema_source);
|
||||
assert_eq!(upstream.len(), FROZEN_SCHEMA_VERSION as usize);
|
||||
assert_eq!(MIGRATIONS.len(), upstream.len());
|
||||
|
||||
for (index, ((up_name, up_sql), &(local_name, local_sql, _))) in
|
||||
upstream.iter().zip(MIGRATIONS.iter()).enumerate()
|
||||
{
|
||||
assert_eq!(
|
||||
local_name,
|
||||
up_name,
|
||||
"migration #{} name mismatch",
|
||||
index + 1
|
||||
);
|
||||
let up_hash = Sha256::digest(up_sql.as_bytes());
|
||||
let local_hash = Sha256::digest(local_sql.as_bytes());
|
||||
assert_eq!(
|
||||
local_hash,
|
||||
up_hash,
|
||||
"migration #{} ({local_name}) SQL SHA-256 mismatch",
|
||||
index + 1
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
pub mod blob;
|
||||
pub mod doc;
|
||||
pub mod migrations;
|
||||
pub mod paths;
|
||||
pub mod storage;
|
||||
pub mod sync;
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use chrono::{DateTime, NaiveDateTime};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub use doc::merge_updates;
|
||||
pub use migrations::{FROZEN_SCHEMA_VERSION, MIGRATIONS, get_migrator};
|
||||
pub use paths::{
|
||||
resolve_allowlisted_workspace_paths, resolve_workspace_db_path, sanitize_peer_name,
|
||||
};
|
||||
pub use storage::SqliteDocStorage;
|
||||
|
||||
/// Convert Unix epoch milliseconds to a UTC `NaiveDateTime`.
|
||||
pub fn millis_to_naive_utc(ms: i64) -> NaiveDateTime {
|
||||
DateTime::from_timestamp_millis(ms)
|
||||
.unwrap_or(DateTime::UNIX_EPOCH)
|
||||
.naive_utc()
|
||||
}
|
||||
|
||||
/// Convert a UTC `NaiveDateTime` to Unix epoch milliseconds.
|
||||
pub fn naive_utc_to_millis(ts: NaiveDateTime) -> i64 {
|
||||
ts.and_utc().timestamp_millis()
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct DocUpdate {
|
||||
pub doc_id: String,
|
||||
pub timestamp: NaiveDateTime,
|
||||
pub bin: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct DocRecord {
|
||||
pub doc_id: String,
|
||||
pub bin: Vec<u8>,
|
||||
pub timestamp: NaiveDateTime,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct DocDiff {
|
||||
pub doc_id: String,
|
||||
pub missing: Vec<u8>,
|
||||
pub state: Vec<u8>,
|
||||
pub timestamp: NaiveDateTime,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct DocClock {
|
||||
pub doc_id: String,
|
||||
pub timestamp: NaiveDateTime,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct SetBlob {
|
||||
pub key: String,
|
||||
pub data: Vec<u8>,
|
||||
pub mime: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct BlobRecord {
|
||||
pub key: String,
|
||||
pub data: Vec<u8>,
|
||||
pub mime: String,
|
||||
pub size: i64,
|
||||
pub created_at: NaiveDateTime,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct ListedBlob {
|
||||
pub key: String,
|
||||
pub size: i64,
|
||||
pub mime: String,
|
||||
pub created_at: NaiveDateTime,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WorkspaceDocInventory {
|
||||
pub doc_id: String,
|
||||
pub timestamp: i64,
|
||||
pub lifecycle: Option<String>,
|
||||
pub lifecycle_changed_at: Option<i64>,
|
||||
#[serde(default)]
|
||||
pub pending_create: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PeerWorkspaceState {
|
||||
pub cache_token: i64,
|
||||
pub ready: bool,
|
||||
pub docs: Vec<WorkspaceDocInventory>,
|
||||
pub clocks: HashMap<String, i64>,
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::error::{StoreError, StoreResult};
|
||||
|
||||
const FORBIDDEN_PEER_CHARS: &[char] = &[
|
||||
'/', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '+', '~', '`', '"', '\'', ':', ';', ',',
|
||||
'?', '<', '>', '|',
|
||||
];
|
||||
|
||||
/// Sanitize a peer name identically to the iOS (`NBStorePlugin.swift`) and Android
|
||||
/// (`NbStorePlugin.kt`) 0.27.4 / 0.27.5 clients:
|
||||
///
|
||||
/// 1. Replace every character in `[/!@#$%^&*()+~`"':;,?<>|]` with `_`.
|
||||
/// 2. Collapse consecutive `_` runs into a single `_`.
|
||||
/// 3. Trim trailing `_` characters.
|
||||
pub fn sanitize_peer_name(peer: &str) -> String {
|
||||
let mut out = String::with_capacity(peer.len());
|
||||
let mut prev_underscore = false;
|
||||
|
||||
for ch in peer.chars() {
|
||||
let mapped = if FORBIDDEN_PEER_CHARS.contains(&ch) {
|
||||
'_'
|
||||
} else {
|
||||
ch
|
||||
};
|
||||
if mapped == '_' {
|
||||
if !prev_underscore {
|
||||
out.push('_');
|
||||
prev_underscore = true;
|
||||
}
|
||||
} else {
|
||||
out.push(mapped);
|
||||
prev_underscore = false;
|
||||
}
|
||||
}
|
||||
|
||||
while out.ends_with('_') {
|
||||
out.pop();
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
fn validate_path_segment(label: &str, value: &str) -> StoreResult<()> {
|
||||
if value.is_empty()
|
||||
|| value == "."
|
||||
|| value == ".."
|
||||
|| value.contains('/')
|
||||
|| value.contains('\\')
|
||||
|| value.contains('\0')
|
||||
{
|
||||
return Err(StoreError::InvalidPath(format!(
|
||||
"invalid {label} segment: {value:?}"
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resolve the in-place SQLite database path for a single explicitly known workspace:
|
||||
/// `<base_dir>/workspaces/<space_type>/<sanitized_peer>/<space_id>.db`.
|
||||
///
|
||||
/// Safety invariant (F1): mobile deletion removes workspace IDs from client state
|
||||
/// without deleting `.db` files on disk. Callers must only open workspace IDs from
|
||||
/// an explicit allowlist and must never scan directories for `*.db` files.
|
||||
pub fn resolve_workspace_db_path(
|
||||
base_dir: &Path,
|
||||
space_type: &str,
|
||||
peer: &str,
|
||||
space_id: &str,
|
||||
) -> StoreResult<PathBuf> {
|
||||
validate_path_segment("space_type", space_type)?;
|
||||
validate_path_segment("space_id", space_id)?;
|
||||
let sanitized_peer = sanitize_peer_name(peer);
|
||||
validate_path_segment("peer", &sanitized_peer)?;
|
||||
|
||||
Ok(base_dir
|
||||
.join("workspaces")
|
||||
.join(space_type)
|
||||
.join(sanitized_peer)
|
||||
.join(format!("{space_id}.db")))
|
||||
}
|
||||
|
||||
/// Resolve paths for an explicit allowlist of workspace IDs without touching the filesystem.
|
||||
///
|
||||
/// This API intentionally does not scan disk directories for `*.db` files so that
|
||||
/// previously deleted workspaces are never resurrected.
|
||||
pub fn resolve_allowlisted_workspace_paths(
|
||||
base_dir: &Path,
|
||||
space_type: &str,
|
||||
peer: &str,
|
||||
allowlisted_space_ids: &[&str],
|
||||
) -> StoreResult<Vec<(String, PathBuf)>> {
|
||||
let mut resolved = Vec::with_capacity(allowlisted_space_ids.len());
|
||||
for space_id in allowlisted_space_ids {
|
||||
let path = resolve_workspace_db_path(base_dir, space_type, peer, space_id)?;
|
||||
resolved.push(((*space_id).to_string(), path));
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sanitize_peer_name_matches_ios_and_android_rules() {
|
||||
let cases = [
|
||||
("local", "local"),
|
||||
("https://app.affine.pro", "https_app.affine.pro"),
|
||||
(
|
||||
"https://self-host.example.com:3010/",
|
||||
"https_self-host.example.com_3010",
|
||||
),
|
||||
(
|
||||
"http://127.0.0.1:8080/api?a=1&b=2",
|
||||
"http_127.0.0.1_8080_api_a=1_b=2",
|
||||
),
|
||||
("a///b___c!!!", "a_b_c"),
|
||||
("peer@host#1+2", "peer_host_1_2"),
|
||||
("plain_name___", "plain_name"),
|
||||
("_leading_preserved", "_leading_preserved"),
|
||||
];
|
||||
|
||||
for (raw, expected) in cases {
|
||||
assert_eq!(sanitize_peer_name(raw), expected, "peer={raw}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_workspace_db_path_enforces_layout_and_rejects_traversal() {
|
||||
let base = Path::new("/data/affine");
|
||||
let path = resolve_workspace_db_path(base, "workspace", "https://app.affine.pro", "ws-123")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
path,
|
||||
PathBuf::from("/data/affine/workspaces/workspace/https_app.affine.pro/ws-123.db")
|
||||
);
|
||||
|
||||
let allowlisted =
|
||||
resolve_allowlisted_workspace_paths(base, "workspace", "local", &["ws-1", "ws-2"])
|
||||
.unwrap();
|
||||
assert_eq!(allowlisted.len(), 2);
|
||||
assert_eq!(
|
||||
allowlisted[0].1,
|
||||
PathBuf::from("/data/affine/workspaces/workspace/local/ws-1.db")
|
||||
);
|
||||
|
||||
assert!(resolve_workspace_db_path(base, "workspace", "local", "../escape").is_err());
|
||||
assert!(resolve_workspace_db_path(base, "../bad", "local", "ws-1").is_err());
|
||||
assert!(resolve_workspace_db_path(base, "workspace", "///", "ws-1").is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,461 @@
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use sqlx::{
|
||||
Pool, Row,
|
||||
migrate::MigrateDatabase,
|
||||
sqlite::{
|
||||
Sqlite, SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous,
|
||||
},
|
||||
};
|
||||
|
||||
use super::migrations::{get_migrator, try_repair_migration_3_checksum};
|
||||
use crate::error::StoreResult;
|
||||
|
||||
/// Macro-free SQLite workspace storage engine compatible with 0.27.4 / 0.27.5 in-place databases.
|
||||
pub struct SqliteDocStorage {
|
||||
pub(super) pool: Pool<Sqlite>,
|
||||
path: String,
|
||||
}
|
||||
|
||||
impl SqliteDocStorage {
|
||||
/// Prepare a lazy SQLite connection pool configured with WAL, `synchronous = FULL`,
|
||||
/// and `foreign_keys = ON`.
|
||||
pub fn new(path: impl Into<String>) -> Self {
|
||||
let path = path.into();
|
||||
let base_options = SqliteConnectOptions::new()
|
||||
.filename(&path)
|
||||
.foreign_keys(true)
|
||||
.synchronous(SqliteSynchronous::Full);
|
||||
|
||||
if path == ":memory:" {
|
||||
let pool = SqlitePoolOptions::new()
|
||||
.min_connections(1)
|
||||
.max_connections(1)
|
||||
.idle_timeout(None)
|
||||
.max_lifetime(None)
|
||||
.connect_lazy_with(base_options);
|
||||
Self { pool, path }
|
||||
} else {
|
||||
let pool = SqlitePoolOptions::new()
|
||||
.max_connections(4)
|
||||
.connect_lazy_with(base_options.journal_mode(SqliteJournalMode::Wal));
|
||||
Self { pool, path }
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the underlying database path string.
|
||||
pub fn path(&self) -> &str {
|
||||
&self.path
|
||||
}
|
||||
|
||||
/// Create the database if missing and apply the frozen 5-step migrations,
|
||||
/// repairing the historical migration #3 trailing-space checksum if needed.
|
||||
pub async fn connect(&self) -> StoreResult<()> {
|
||||
if self.path != ":memory:" && !Sqlite::database_exists(&self.path).await? {
|
||||
Sqlite::create_database(&self.path).await?;
|
||||
}
|
||||
self.migrate().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn migrate(&self) -> StoreResult<()> {
|
||||
let migrator = get_migrator();
|
||||
if let Err(err) = migrator.run(&self.pool).await {
|
||||
if matches!(err, sqlx::migrate::MigrateError::VersionMismatch(3))
|
||||
&& try_repair_migration_3_checksum(&self.pool, &migrator).await?
|
||||
{
|
||||
migrator.run(&self.pool).await?;
|
||||
} else {
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Close the connection pool cleanly.
|
||||
pub async fn close(&self) {
|
||||
self.pool.close().await;
|
||||
}
|
||||
|
||||
/// Return whether the connection pool has been closed.
|
||||
pub fn is_closed(&self) -> bool {
|
||||
self.pool.is_closed()
|
||||
}
|
||||
|
||||
/// Flush the WAL journal into the main database file.
|
||||
pub async fn checkpoint(&self) -> StoreResult<()> {
|
||||
sqlx::query("PRAGMA wal_checkpoint(FULL);")
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Export a compacted copy of the database to `target_path`.
|
||||
pub async fn vacuum_into(&self, target_path: &str) -> StoreResult<()> {
|
||||
sqlx::query("VACUUM INTO ?;")
|
||||
.bind(target_path)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Verify that all required v2/v5 tables exist on the connected database.
|
||||
pub async fn validate_required_tables(&self) -> StoreResult<bool> {
|
||||
let rows = sqlx::query("SELECT name FROM sqlite_schema WHERE type = 'table'")
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
let mut names = BTreeSet::new();
|
||||
for row in rows {
|
||||
let name: String = row.try_get("name")?;
|
||||
names.insert(name);
|
||||
}
|
||||
let required = [
|
||||
"meta",
|
||||
"snapshots",
|
||||
"updates",
|
||||
"clocks",
|
||||
"blobs",
|
||||
"peer_clocks",
|
||||
"peer_blob_sync",
|
||||
"idx_snapshots",
|
||||
"indexer_sync",
|
||||
];
|
||||
Ok(required.iter().all(|table| names.contains(*table)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::borrow::Cow;
|
||||
|
||||
use sqlx::migrate::{Migration, Migrator};
|
||||
|
||||
use super::*;
|
||||
use crate::{
|
||||
directory::{CreateDocId, CreateDocRequest, DocMode, WorkspaceDirectory},
|
||||
sqlite::{SetBlob, millis_to_naive_utc},
|
||||
workspace_db::{PageIdSource, WorkspaceDb, WorkspaceDbTableName},
|
||||
};
|
||||
|
||||
#[tokio::test]
|
||||
async fn upgrades_0274_db_with_legacy_migration_3_checksum_and_preserves_data() {
|
||||
let temp_path = std::env::temp_dir().join(format!(
|
||||
"affine-store-upgrade-test-{}.db",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = std::fs::remove_file(&temp_path);
|
||||
let _ = std::fs::remove_file(format!("{}-wal", temp_path.display()));
|
||||
let _ = std::fs::remove_file(format!("{}-shm", temp_path.display()));
|
||||
|
||||
let path_str = temp_path.to_string_lossy().to_string();
|
||||
let storage = SqliteDocStorage::new(&path_str);
|
||||
Sqlite::create_database(&path_str).await.unwrap();
|
||||
|
||||
// Simulate 0.27.4: only 4 migrations applied, and migration #3 had a trailing space.
|
||||
let full_migrator = get_migrator();
|
||||
let mut legacy_migrations = full_migrator.migrations.to_vec();
|
||||
let mig3 = legacy_migrations[2].clone();
|
||||
legacy_migrations[2] = Migration::new(
|
||||
mig3.version,
|
||||
mig3.description.clone(),
|
||||
mig3.migration_type,
|
||||
Cow::Owned(format!("{} ", mig3.sql)),
|
||||
mig3.no_tx,
|
||||
);
|
||||
legacy_migrations.truncate(4);
|
||||
let legacy_migrator = Migrator {
|
||||
migrations: Cow::Owned(legacy_migrations),
|
||||
..Migrator::DEFAULT
|
||||
};
|
||||
legacy_migrator.run(&storage.pool).await.unwrap();
|
||||
|
||||
storage.set_space_id("ws-0274").await.unwrap();
|
||||
let doc_ts = storage
|
||||
.push_update("doc-legacy", [0u8, 0u8], 1_700_000_000_000)
|
||||
.await
|
||||
.unwrap();
|
||||
storage
|
||||
.set_blob(SetBlob {
|
||||
key: "blob-1".to_string(),
|
||||
data: vec![1, 2, 3, 4],
|
||||
mime: "application/octet-stream".to_string(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
storage
|
||||
.set_peer_remote_clock(
|
||||
"cloud",
|
||||
"doc-legacy",
|
||||
millis_to_naive_utc(1_700_000_000_500),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
storage.close().await;
|
||||
|
||||
let upgraded = SqliteDocStorage::new(&path_str);
|
||||
upgraded.connect().await.unwrap();
|
||||
assert!(upgraded.validate_required_tables().await.unwrap());
|
||||
|
||||
let journal: String = sqlx::query("PRAGMA journal_mode;")
|
||||
.fetch_one(&upgraded.pool)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_get(0)
|
||||
.unwrap();
|
||||
assert_eq!(journal.to_ascii_lowercase(), "wal");
|
||||
let fk: i64 = sqlx::query("PRAGMA foreign_keys;")
|
||||
.fetch_one(&upgraded.pool)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_get(0)
|
||||
.unwrap();
|
||||
assert_eq!(fk, 1);
|
||||
let sync_mode: i64 = sqlx::query("PRAGMA synchronous;")
|
||||
.fetch_one(&upgraded.pool)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_get(0)
|
||||
.unwrap();
|
||||
assert_eq!(sync_mode, 2);
|
||||
|
||||
let max_version: i64 = sqlx::query("SELECT MAX(version) FROM _sqlx_migrations")
|
||||
.fetch_one(&upgraded.pool)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_get(0)
|
||||
.unwrap();
|
||||
assert_eq!(max_version, 5);
|
||||
|
||||
let rec = upgraded.get_doc("doc-legacy").await.unwrap().unwrap();
|
||||
assert_eq!(rec.timestamp, doc_ts);
|
||||
let blob = upgraded.get_blob("blob-1").await.unwrap().unwrap();
|
||||
assert_eq!(blob.data, vec![1, 2, 3, 4]);
|
||||
let clock = upgraded
|
||||
.get_peer_remote_clock("cloud", "doc-legacy")
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(clock.timestamp, millis_to_naive_utc(1_700_000_000_500));
|
||||
|
||||
upgraded.checkpoint().await.unwrap();
|
||||
upgraded.close().await;
|
||||
|
||||
let reopened = SqliteDocStorage::new(&path_str);
|
||||
reopened.connect().await.unwrap();
|
||||
assert!(reopened.get_doc("doc-legacy").await.unwrap().is_some());
|
||||
reopened.close().await;
|
||||
|
||||
let _ = std::fs::remove_file(&temp_path);
|
||||
let _ = std::fs::remove_file(format!("{}-wal", temp_path.display()));
|
||||
let _ = std::fs::remove_file(format!("{}-shm", temp_path.display()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn deterministic_op_id_and_atomic_batch_persist_edgeless_across_restart() {
|
||||
let storage = SqliteDocStorage::new(":memory:");
|
||||
storage.connect().await.unwrap();
|
||||
storage.set_space_id("ws-idem").await.unwrap();
|
||||
|
||||
let mut db = WorkspaceDb::new("ws-idem", "u1", 1);
|
||||
db.initialize_meta().unwrap();
|
||||
let mut dir = WorkspaceDirectory::new(db);
|
||||
let created = dir
|
||||
.create_doc(CreateDocRequest {
|
||||
id: CreateDocId::from_op("op-1").unwrap(),
|
||||
title: "Spec".into(),
|
||||
mode: DocMode::Edgeless,
|
||||
now_ms: 1_000,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(created.created_new);
|
||||
let original_page_id = created.doc_id.clone();
|
||||
|
||||
// Atomically commit ws-idem initialize_meta, ws-idem create_page, and db$docProperties in one SQLite tx.
|
||||
let batch = dir.drain_pending_updates();
|
||||
let committed = storage
|
||||
.push_updates_batch(&batch, Some("cloud"), 1_000)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(committed.len(), 3);
|
||||
|
||||
// Reload fresh WorkspaceDb + db$docProperties from SQLite: Edgeless mode & idempotency hold.
|
||||
let loaded_rec = storage.get_doc("ws-idem").await.unwrap().unwrap();
|
||||
let loaded_props = storage.get_doc("db$docProperties").await.unwrap().unwrap();
|
||||
let mut reloaded_db =
|
||||
WorkspaceDb::from_root_update_v1("ws-idem", "u1", 2, &loaded_rec.bin).unwrap();
|
||||
reloaded_db
|
||||
.load_db_table(WorkspaceDbTableName::DocProperties, &loaded_props.bin)
|
||||
.unwrap();
|
||||
let sv_before = reloaded_db.root().encode_state_vector_v1().unwrap();
|
||||
let mut reloaded_dir = WorkspaceDirectory::new(reloaded_db);
|
||||
assert_eq!(
|
||||
reloaded_dir
|
||||
.get_doc(&original_page_id)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.mode,
|
||||
DocMode::Edgeless
|
||||
);
|
||||
|
||||
let retry = reloaded_dir
|
||||
.create_doc(CreateDocRequest {
|
||||
id: CreateDocId::from_op("op-1").unwrap(),
|
||||
title: "Spec".into(),
|
||||
mode: DocMode::Edgeless,
|
||||
now_ms: 2_000,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(!retry.created_new);
|
||||
assert_eq!(retry.doc_id, original_page_id);
|
||||
assert!(reloaded_dir.drain_pending_updates().is_empty());
|
||||
assert_eq!(reloaded_dir.db().root().list_pages().unwrap().len(), 1);
|
||||
assert_eq!(
|
||||
reloaded_dir.db().root().encode_state_vector_v1().unwrap(),
|
||||
sv_before
|
||||
);
|
||||
|
||||
// Even after trashing the page and reloading, retrying op-1 must still be idempotent.
|
||||
reloaded_dir.trash_doc(&original_page_id, 2_500).unwrap();
|
||||
let trashed_bytes = reloaded_dir.db().root().encode_update_v1().unwrap();
|
||||
let mut after_trash =
|
||||
WorkspaceDb::from_root_update_v1("ws-idem", "u1", 3, &trashed_bytes).unwrap();
|
||||
let retry_trashed = after_trash
|
||||
.create_page(PageIdSource::DerivedFromOp("op-1"), "Spec", 3_000)
|
||||
.unwrap();
|
||||
assert!(!retry_trashed.created_new);
|
||||
assert_eq!(retry_trashed.page_id, original_page_id.as_str());
|
||||
assert!(retry_trashed.update.is_none());
|
||||
assert!(after_trash.drain_pending_updates().is_empty());
|
||||
assert_eq!(after_trash.root().list_pages().unwrap().len(), 1);
|
||||
|
||||
// Ensure raw encoded Yjs bytes never contain "createOpId" and idx_snapshots stayed untouched.
|
||||
assert!(
|
||||
!loaded_rec
|
||||
.bin
|
||||
.windows("createOpId".len())
|
||||
.any(|w| w == b"createOpId"),
|
||||
"shared Yjs root bytes must not contain createOpId"
|
||||
);
|
||||
let idx_count: i64 = sqlx::query("SELECT COUNT(*) FROM idx_snapshots")
|
||||
.fetch_one(&storage.pool)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_get(0)
|
||||
.unwrap();
|
||||
assert_eq!(idx_count, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn interleaved_connections_and_uncheckpointed_wal_recovery() {
|
||||
let temp_path = std::env::temp_dir().join(format!(
|
||||
"affine-store-wal-recovery-{}.db",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = std::fs::remove_file(&temp_path);
|
||||
let _ = std::fs::remove_file(format!("{}-wal", temp_path.display()));
|
||||
let _ = std::fs::remove_file(format!("{}-shm", temp_path.display()));
|
||||
|
||||
let path_str = temp_path.to_string_lossy().to_string();
|
||||
let writer_a = SqliteDocStorage::new(&path_str);
|
||||
writer_a.connect().await.unwrap();
|
||||
let writer_b = SqliteDocStorage::new(&path_str);
|
||||
writer_b.connect().await.unwrap();
|
||||
|
||||
writer_a
|
||||
.push_update("shared-doc", [0u8, 0u8], 1_000)
|
||||
.await
|
||||
.unwrap();
|
||||
writer_b
|
||||
.set_blob(SetBlob {
|
||||
key: "shared-blob".into(),
|
||||
data: vec![7, 8, 9],
|
||||
mime: "application/octet-stream".into(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(writer_a.get_blob("shared-blob").await.unwrap().is_some());
|
||||
assert!(writer_b.get_doc("shared-doc").await.unwrap().is_some());
|
||||
|
||||
drop(writer_a);
|
||||
drop(writer_b);
|
||||
|
||||
let recovered = SqliteDocStorage::new(&path_str);
|
||||
recovered.connect().await.unwrap();
|
||||
assert!(recovered.get_doc("shared-doc").await.unwrap().is_some());
|
||||
assert_eq!(
|
||||
recovered
|
||||
.get_blob("shared-blob")
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.data,
|
||||
vec![7, 8, 9]
|
||||
);
|
||||
recovered.close().await;
|
||||
|
||||
let _ = std::fs::remove_file(&temp_path);
|
||||
let _ = std::fs::remove_file(format!("{}-wal", temp_path.display()));
|
||||
let _ = std::fs::remove_file(format!("{}-shm", temp_path.display()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn push_updates_batch_begin_immediate_avoids_wal_busy_snapshot_under_concurrency() {
|
||||
let temp_path =
|
||||
std::env::temp_dir().join(format!("affine-store-batch-wal-{}.db", std::process::id()));
|
||||
let _ = std::fs::remove_file(&temp_path);
|
||||
let _ = std::fs::remove_file(format!("{}-wal", temp_path.display()));
|
||||
let _ = std::fs::remove_file(format!("{}-shm", temp_path.display()));
|
||||
|
||||
let path_str = temp_path.to_string_lossy().to_string();
|
||||
let storage = SqliteDocStorage::new(&path_str);
|
||||
storage.connect().await.unwrap();
|
||||
storage.set_space_id("ws-conc").await.unwrap();
|
||||
|
||||
let make_non_empty_update = |client_id: u64, key: &str, val: &str| -> Vec<u8> {
|
||||
let doc = y_octo::DocOptions::from_identity(client_id, "ws-conc".to_string()).build();
|
||||
let mut map = doc.get_or_create_map("m").unwrap();
|
||||
map.insert(
|
||||
key.to_string(),
|
||||
y_octo::Value::Any(y_octo::Any::String(val.to_string())),
|
||||
)
|
||||
.unwrap();
|
||||
doc.encode_update_v1().unwrap()
|
||||
};
|
||||
|
||||
for round in 0..8u64 {
|
||||
let b1 = vec![
|
||||
crate::workspace_db::PendingDocUpdate {
|
||||
doc_id: "ws-conc".into(),
|
||||
update: make_non_empty_update(10 + round * 3, "k1", "v1"),
|
||||
},
|
||||
crate::workspace_db::PendingDocUpdate {
|
||||
doc_id: "db$docProperties".into(),
|
||||
update: make_non_empty_update(11 + round * 3, "k2", "v2"),
|
||||
},
|
||||
];
|
||||
let b2 = vec![crate::workspace_db::PendingDocUpdate {
|
||||
doc_id: "ws-conc".into(),
|
||||
update: make_non_empty_update(12 + round * 3, "k3", "v3"),
|
||||
}];
|
||||
let single = make_non_empty_update(100 + round, "ks", "vs");
|
||||
let base_ms = 10_000 + (round as i64) * 10;
|
||||
|
||||
let (r1, r2, r3) = tokio::join!(
|
||||
storage.push_updates_batch(&b1, Some("cloud"), base_ms),
|
||||
storage.push_updates_batch(&b2, None, base_ms),
|
||||
storage.push_update("ws-conc", single, base_ms),
|
||||
);
|
||||
assert_eq!(r1.unwrap().len(), 2);
|
||||
assert_eq!(r2.unwrap().len(), 1);
|
||||
r3.unwrap();
|
||||
}
|
||||
|
||||
assert!(storage.get_doc("ws-conc").await.unwrap().is_some());
|
||||
assert!(storage.get_doc("db$docProperties").await.unwrap().is_some());
|
||||
storage.close().await;
|
||||
|
||||
let _ = std::fs::remove_file(&temp_path);
|
||||
let _ = std::fs::remove_file(format!("{}-wal", temp_path.display()));
|
||||
let _ = std::fs::remove_file(format!("{}-shm", temp_path.display()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,406 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use chrono::NaiveDateTime;
|
||||
use sqlx::Row;
|
||||
|
||||
use super::{
|
||||
DocClock, PeerWorkspaceState, SqliteDocStorage, WorkspaceDocInventory, millis_to_naive_utc,
|
||||
naive_utc_to_millis,
|
||||
};
|
||||
use crate::error::StoreResult;
|
||||
|
||||
fn row_to_doc_clock(row: &sqlx::sqlite::SqliteRow) -> StoreResult<DocClock> {
|
||||
Ok(DocClock {
|
||||
doc_id: row.try_get("doc_id")?,
|
||||
timestamp: row.try_get("timestamp")?,
|
||||
})
|
||||
}
|
||||
|
||||
impl SqliteDocStorage {
|
||||
pub async fn get_peer_remote_clocks(&self, peer: &str) -> StoreResult<Vec<DocClock>> {
|
||||
let rows =
|
||||
sqlx::query("SELECT doc_id, remote_clock AS timestamp FROM peer_clocks WHERE peer = ?")
|
||||
.bind(peer)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
rows.iter().map(row_to_doc_clock).collect()
|
||||
}
|
||||
|
||||
pub async fn get_peer_remote_clock(
|
||||
&self,
|
||||
peer: &str,
|
||||
doc_id: &str,
|
||||
) -> StoreResult<Option<DocClock>> {
|
||||
let row = sqlx::query(
|
||||
"SELECT doc_id, remote_clock AS timestamp FROM peer_clocks \
|
||||
WHERE peer = ? AND doc_id = ?",
|
||||
)
|
||||
.bind(peer)
|
||||
.bind(doc_id)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
row.as_ref().map(row_to_doc_clock).transpose()
|
||||
}
|
||||
|
||||
pub async fn set_peer_remote_clock(
|
||||
&self,
|
||||
peer: &str,
|
||||
doc_id: &str,
|
||||
clock: NaiveDateTime,
|
||||
) -> StoreResult<()> {
|
||||
sqlx::query(
|
||||
"INSERT INTO peer_clocks (peer, doc_id, remote_clock) VALUES ($1, $2, $3) \
|
||||
ON CONFLICT(peer, doc_id) DO UPDATE SET remote_clock = $3 WHERE remote_clock < $3;",
|
||||
)
|
||||
.bind(peer)
|
||||
.bind(doc_id)
|
||||
.bind(clock)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get_peer_pulled_remote_clocks(&self, peer: &str) -> StoreResult<Vec<DocClock>> {
|
||||
let rows = sqlx::query(
|
||||
"SELECT doc_id, pulled_remote_clock AS timestamp FROM peer_clocks WHERE peer = ?",
|
||||
)
|
||||
.bind(peer)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
rows.iter().map(row_to_doc_clock).collect()
|
||||
}
|
||||
|
||||
pub async fn get_peer_pulled_remote_clock(
|
||||
&self,
|
||||
peer: &str,
|
||||
doc_id: &str,
|
||||
) -> StoreResult<Option<DocClock>> {
|
||||
let row = sqlx::query(
|
||||
"SELECT doc_id, pulled_remote_clock AS timestamp FROM peer_clocks \
|
||||
WHERE peer = ? AND doc_id = ?",
|
||||
)
|
||||
.bind(peer)
|
||||
.bind(doc_id)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
row.as_ref().map(row_to_doc_clock).transpose()
|
||||
}
|
||||
|
||||
pub async fn set_peer_pulled_remote_clock(
|
||||
&self,
|
||||
peer: &str,
|
||||
doc_id: &str,
|
||||
clock: NaiveDateTime,
|
||||
) -> StoreResult<()> {
|
||||
sqlx::query(
|
||||
"INSERT INTO peer_clocks (peer, doc_id, pulled_remote_clock) VALUES ($1, $2, $3) \
|
||||
ON CONFLICT(peer, doc_id) DO UPDATE SET pulled_remote_clock = $3 \
|
||||
WHERE pulled_remote_clock < $3;",
|
||||
)
|
||||
.bind(peer)
|
||||
.bind(doc_id)
|
||||
.bind(clock)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get_peer_pushed_clocks(&self, peer: &str) -> StoreResult<Vec<DocClock>> {
|
||||
let rows =
|
||||
sqlx::query("SELECT doc_id, pushed_clock AS timestamp FROM peer_clocks WHERE peer = ?")
|
||||
.bind(peer)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
rows.iter().map(row_to_doc_clock).collect()
|
||||
}
|
||||
|
||||
pub async fn get_peer_pushed_clock(
|
||||
&self,
|
||||
peer: &str,
|
||||
doc_id: &str,
|
||||
) -> StoreResult<Option<DocClock>> {
|
||||
let row = sqlx::query(
|
||||
"SELECT doc_id, pushed_clock AS timestamp FROM peer_clocks \
|
||||
WHERE peer = ? AND doc_id = ?",
|
||||
)
|
||||
.bind(peer)
|
||||
.bind(doc_id)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
row.as_ref().map(row_to_doc_clock).transpose()
|
||||
}
|
||||
|
||||
pub async fn set_peer_pushed_clock(
|
||||
&self,
|
||||
peer: &str,
|
||||
doc_id: &str,
|
||||
clock: NaiveDateTime,
|
||||
) -> StoreResult<()> {
|
||||
sqlx::query(
|
||||
"INSERT INTO peer_clocks (peer, doc_id, pushed_clock) VALUES ($1, $2, $3) \
|
||||
ON CONFLICT(peer, doc_id) DO UPDATE SET pushed_clock = $3 WHERE pushed_clock < $3;",
|
||||
)
|
||||
.bind(peer)
|
||||
.bind(doc_id)
|
||||
.bind(clock)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get_peer_workspace_state(
|
||||
&self,
|
||||
peer: &str,
|
||||
root_doc_id: &str,
|
||||
) -> StoreResult<PeerWorkspaceState> {
|
||||
let mut tx = self.pool.begin().await?;
|
||||
let records = sqlx::query(
|
||||
"SELECT doc_id, remote_clock, inventory_kind, lifecycle, lifecycle_changed_at, \
|
||||
pending_create, inventory_ready, cache_token FROM peer_clocks WHERE peer = ?",
|
||||
)
|
||||
.bind(peer)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?;
|
||||
|
||||
let mut state = PeerWorkspaceState {
|
||||
cache_token: 0,
|
||||
ready: false,
|
||||
docs: Vec::new(),
|
||||
clocks: HashMap::new(),
|
||||
};
|
||||
|
||||
for record in records {
|
||||
let doc_id: String = record.try_get("doc_id")?;
|
||||
if doc_id == root_doc_id {
|
||||
state.cache_token = record.try_get("cache_token")?;
|
||||
state.ready = record.try_get("inventory_ready")?;
|
||||
}
|
||||
let kind: Option<String> = record.try_get("inventory_kind")?;
|
||||
let pending: bool = record.try_get("pending_create")?;
|
||||
let remote_clock: NaiveDateTime = record.try_get("remote_clock")?;
|
||||
let timestamp = naive_utc_to_millis(remote_clock);
|
||||
|
||||
if kind.as_deref() == Some("doc") || pending {
|
||||
state.docs.push(WorkspaceDocInventory {
|
||||
doc_id,
|
||||
timestamp,
|
||||
lifecycle: record.try_get("lifecycle")?,
|
||||
lifecycle_changed_at: record.try_get("lifecycle_changed_at")?,
|
||||
pending_create: pending,
|
||||
});
|
||||
} else if kind.as_deref() == Some("reserved") {
|
||||
state.clocks.insert(doc_id, timestamp);
|
||||
}
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
pub async fn invalidate_peer_workspace_state(
|
||||
&self,
|
||||
peer: &str,
|
||||
root_doc_id: &str,
|
||||
) -> StoreResult<()> {
|
||||
sqlx::query(
|
||||
"INSERT INTO peer_clocks (peer, doc_id, cache_token) VALUES ($1, $2, 1) \
|
||||
ON CONFLICT(peer, doc_id) DO UPDATE SET cache_token = cache_token + 1",
|
||||
)
|
||||
.bind(peer)
|
||||
.bind(root_doc_id)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn install_peer_workspace_state(
|
||||
&self,
|
||||
peer: &str,
|
||||
root_doc_id: &str,
|
||||
cache_token: i64,
|
||||
docs: &[WorkspaceDocInventory],
|
||||
clocks: &HashMap<String, i64>,
|
||||
) -> StoreResult<bool> {
|
||||
let mut tx = self.pool.begin().await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO peer_clocks (peer, doc_id) VALUES ($1, $2) \
|
||||
ON CONFLICT(peer, doc_id) DO NOTHING",
|
||||
)
|
||||
.bind(peer)
|
||||
.bind(root_doc_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
let installed = sqlx::query(
|
||||
"UPDATE peer_clocks SET cache_token = cache_token + 1, inventory_ready = TRUE \
|
||||
WHERE peer = $1 AND doc_id = $2 AND cache_token = $3",
|
||||
)
|
||||
.bind(peer)
|
||||
.bind(root_doc_id)
|
||||
.bind(cache_token)
|
||||
.execute(&mut *tx)
|
||||
.await?
|
||||
.rows_affected();
|
||||
if installed == 0 {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
sqlx::query(
|
||||
"UPDATE peer_clocks SET inventory_kind = NULL, lifecycle = NULL, \
|
||||
lifecycle_changed_at = NULL WHERE peer = ?",
|
||||
)
|
||||
.bind(peer)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
for (doc_id, timestamp) in clocks {
|
||||
sqlx::query(
|
||||
"INSERT INTO peer_clocks (peer, doc_id, remote_clock, inventory_kind) \
|
||||
VALUES ($1, $2, $3, 'reserved') \
|
||||
ON CONFLICT(peer, doc_id) DO UPDATE SET \
|
||||
remote_clock = MAX(remote_clock, excluded.remote_clock), \
|
||||
inventory_kind = 'reserved'",
|
||||
)
|
||||
.bind(peer)
|
||||
.bind(doc_id)
|
||||
.bind(millis_to_naive_utc(*timestamp))
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
|
||||
for doc in docs {
|
||||
sqlx::query(
|
||||
"INSERT INTO peer_clocks (\
|
||||
peer, doc_id, remote_clock, inventory_kind, lifecycle, lifecycle_changed_at\
|
||||
) VALUES ($1, $2, $3, 'doc', $4, $5) \
|
||||
ON CONFLICT(peer, doc_id) DO UPDATE SET \
|
||||
remote_clock = MAX(remote_clock, excluded.remote_clock), \
|
||||
inventory_kind = 'doc', \
|
||||
lifecycle = excluded.lifecycle, \
|
||||
lifecycle_changed_at = excluded.lifecycle_changed_at",
|
||||
)
|
||||
.bind(peer)
|
||||
.bind(&doc.doc_id)
|
||||
.bind(millis_to_naive_utc(doc.timestamp))
|
||||
.bind(&doc.lifecycle)
|
||||
.bind(doc.lifecycle_changed_at)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
|
||||
tx.commit().await?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub async fn confirm_peer_doc_create(&self, peer: &str, doc_id: &str) -> StoreResult<()> {
|
||||
let mut tx = self.pool.begin().await?;
|
||||
let changed = sqlx::query(
|
||||
"UPDATE peer_clocks SET pending_create = FALSE \
|
||||
WHERE peer = $1 AND doc_id = $2 AND pending_create = TRUE",
|
||||
)
|
||||
.bind(peer)
|
||||
.bind(doc_id)
|
||||
.execute(&mut *tx)
|
||||
.await?
|
||||
.rows_affected();
|
||||
if changed > 0 {
|
||||
sqlx::query(
|
||||
"INSERT INTO peer_clocks (peer, doc_id, cache_token) \
|
||||
SELECT $1, space_id, 1 FROM meta WHERE TRUE \
|
||||
ON CONFLICT(peer, doc_id) DO UPDATE SET cache_token = cache_token + 1",
|
||||
)
|
||||
.bind(peer)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn clear_clocks(&self) -> StoreResult<()> {
|
||||
let mut tx = self.pool.begin().await?;
|
||||
sqlx::query(
|
||||
"DELETE FROM peer_clocks WHERE inventory_kind IS NULL \
|
||||
AND pending_create = FALSE AND inventory_ready = FALSE AND cache_token = 0",
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"UPDATE peer_clocks SET \
|
||||
remote_clock = CASE WHEN inventory_kind IS NULL THEN 0 ELSE remote_clock END, \
|
||||
pulled_remote_clock = 0, pushed_clock = 0, cache_token = cache_token + 1",
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn peer_clocks_and_workspace_inventory_lifecycle() {
|
||||
let storage = SqliteDocStorage::new(":memory:");
|
||||
storage.connect().await.unwrap();
|
||||
storage.set_space_id("ws-root").await.unwrap();
|
||||
|
||||
storage
|
||||
.push_update_with_peer("doc-new", [0u8, 0u8], Some("acct-1"), 10_000)
|
||||
.await
|
||||
.unwrap();
|
||||
let initial = storage
|
||||
.get_peer_workspace_state("acct-1", "ws-root")
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!initial.ready);
|
||||
assert_eq!(initial.cache_token, 1);
|
||||
assert_eq!(initial.docs.len(), 1);
|
||||
assert!(initial.docs[0].pending_create);
|
||||
|
||||
let installed = storage
|
||||
.install_peer_workspace_state(
|
||||
"acct-1",
|
||||
"ws-root",
|
||||
initial.cache_token,
|
||||
&[WorkspaceDocInventory {
|
||||
doc_id: "doc-remote".into(),
|
||||
timestamp: 20_000,
|
||||
lifecycle: Some("trashed".into()),
|
||||
lifecycle_changed_at: Some(21_000),
|
||||
pending_create: false,
|
||||
}],
|
||||
&HashMap::from([("db$folders".to_string(), 19_000)]),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(installed);
|
||||
|
||||
let after = storage
|
||||
.get_peer_workspace_state("acct-1", "ws-root")
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(after.ready);
|
||||
assert_eq!(after.docs.len(), 2);
|
||||
assert_eq!(after.clocks.get("db$folders"), Some(&19_000));
|
||||
|
||||
storage
|
||||
.confirm_peer_doc_create("acct-1", "doc-new")
|
||||
.await
|
||||
.unwrap();
|
||||
let confirmed = storage
|
||||
.get_peer_workspace_state("acct-1", "ws-root")
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(confirmed.docs.len(), 1);
|
||||
assert_eq!(confirmed.docs[0].doc_id, "doc-remote");
|
||||
|
||||
storage.clear_clocks().await.unwrap();
|
||||
let cleared = storage
|
||||
.get_peer_workspace_state("acct-1", "ws-root")
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(cleared.docs.len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::{
|
||||
DeferredAfterJoin, DocLifecycleAction, DocLifecycleResponse, InFlightRequest,
|
||||
JoinSpaceBatchResponse, LoadDocResponse, PushDocUpdateResponse, SPACE_DELETE_DOC,
|
||||
SPACE_DOC_LIFECYCLE, SPACE_JOIN_BATCH, SPACE_LOAD_DOC, SPACE_LOAD_DOC_TIMESTAMPS,
|
||||
SPACE_PUSH_DOC_UPDATE, SpaceSyncEngine, SpaceSyncEvent, SpaceSyncState, WebsocketResponse,
|
||||
handlers::deferred_doc_id,
|
||||
};
|
||||
|
||||
impl SpaceSyncEngine {
|
||||
pub(super) fn handle_ack(&mut self, ack_id: u64, payload: Value, now_ms: i64) {
|
||||
let Some(pending) = self.in_flight.remove(&ack_id) else {
|
||||
return;
|
||||
};
|
||||
|
||||
match pending.request {
|
||||
InFlightRequest::InitialJoin { root_wire_id } => {
|
||||
match serde_json::from_value::<WebsocketResponse<JoinSpaceBatchResponse>>(payload) {
|
||||
Ok(WebsocketResponse::Ok { data })
|
||||
if data.success
|
||||
&& data.protocol_version == self.config.protocol_version =>
|
||||
{
|
||||
self.joined_doc_ids.insert(root_wire_id);
|
||||
self.state = SpaceSyncState::Ready;
|
||||
self.reconnect_attempts = 0;
|
||||
self.offline_retry_attempts = 0;
|
||||
self.next_offline_retry_at_ms = None;
|
||||
self.waiting_for_id_converter = self.config.defer_offline_replay_on_join;
|
||||
self.events.push(SpaceSyncEvent::Joined {
|
||||
client_id: data.client_id,
|
||||
protocol_version: data.protocol_version,
|
||||
client_version: data.client_version,
|
||||
});
|
||||
if !self.waiting_for_id_converter {
|
||||
self.replay_offline_queue(now_ms);
|
||||
}
|
||||
}
|
||||
Ok(WebsocketResponse::Err { error }) if error.is_permission_revoked() => {
|
||||
let code = error.canonical_code().to_string();
|
||||
self.handle_auth_or_permission_pause(
|
||||
None,
|
||||
&code,
|
||||
error.message,
|
||||
None,
|
||||
now_ms,
|
||||
);
|
||||
}
|
||||
_ => {
|
||||
self.handle_disconnect("space:join-batch rejected", now_ms);
|
||||
}
|
||||
}
|
||||
}
|
||||
InFlightRequest::JoinDocs {
|
||||
wire_doc_ids,
|
||||
deferred,
|
||||
} => {
|
||||
match serde_json::from_value::<WebsocketResponse<JoinSpaceBatchResponse>>(payload) {
|
||||
Ok(WebsocketResponse::Ok { data })
|
||||
if data.success
|
||||
&& data.protocol_version == self.config.protocol_version =>
|
||||
{
|
||||
let mut local_ids = Vec::with_capacity(wire_doc_ids.len());
|
||||
for wire_id in wire_doc_ids {
|
||||
local_ids.push(self.id_converter.old_id_to_new_id(&wire_id));
|
||||
self.joined_doc_ids.insert(wire_id);
|
||||
}
|
||||
self.events
|
||||
.push(SpaceSyncEvent::DocsJoined { doc_ids: local_ids });
|
||||
if let Some(next_op) = deferred {
|
||||
self.run_deferred_after_join(next_op, now_ms);
|
||||
}
|
||||
if self.state == SpaceSyncState::Ready
|
||||
&& !self.waiting_for_id_converter
|
||||
&& self.next_offline_retry_at_ms.is_none()
|
||||
{
|
||||
self.replay_offline_queue(now_ms);
|
||||
}
|
||||
}
|
||||
Ok(WebsocketResponse::Err { error }) if error.is_permission_revoked() => {
|
||||
let doc_id = deferred_doc_id(deferred.as_ref());
|
||||
let code = error.canonical_code().to_string();
|
||||
let failed = match deferred {
|
||||
Some(DeferredAfterJoin::PushDocUpdate { entry, .. }) => {
|
||||
Some((ack_id, entry))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
self.handle_auth_or_permission_pause(
|
||||
doc_id,
|
||||
&code,
|
||||
error.message,
|
||||
failed,
|
||||
now_ms,
|
||||
);
|
||||
}
|
||||
Ok(WebsocketResponse::Err { error }) => {
|
||||
let doc_id = deferred_doc_id(deferred.as_ref());
|
||||
if let Some(DeferredAfterJoin::PushDocUpdate { entry, .. }) = deferred {
|
||||
self.shelve_push_for_retry(entry, now_ms);
|
||||
}
|
||||
self.emit_request_failed(
|
||||
SPACE_JOIN_BATCH,
|
||||
doc_id,
|
||||
error.canonical_code().to_string(),
|
||||
error.message,
|
||||
);
|
||||
}
|
||||
_ => {
|
||||
let doc_id = deferred_doc_id(deferred.as_ref());
|
||||
if let Some(DeferredAfterJoin::PushDocUpdate { entry, .. }) = deferred {
|
||||
self.shelve_push_for_retry(entry, now_ms);
|
||||
}
|
||||
self.emit_request_failed(
|
||||
SPACE_JOIN_BATCH,
|
||||
doc_id,
|
||||
"INVALID_RESPONSE".into(),
|
||||
"space:join-batch rejected".into(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
InFlightRequest::LoadDoc {
|
||||
doc_id,
|
||||
wire_doc_id,
|
||||
state_vector,
|
||||
retried_not_in_space,
|
||||
} => match serde_json::from_value::<WebsocketResponse<LoadDocResponse>>(payload) {
|
||||
Ok(WebsocketResponse::Ok { data }) => {
|
||||
match (BASE64.decode(&data.missing), BASE64.decode(&data.state)) {
|
||||
(Ok(missing), Ok(state)) => {
|
||||
self.events.push(SpaceSyncEvent::DocLoaded {
|
||||
doc_id,
|
||||
missing,
|
||||
state,
|
||||
timestamp: data.timestamp,
|
||||
});
|
||||
}
|
||||
_ => self.emit_request_failed(
|
||||
SPACE_LOAD_DOC,
|
||||
Some(doc_id),
|
||||
"INVALID_BASE64".into(),
|
||||
"invalid base64 in space:load-doc response".into(),
|
||||
),
|
||||
}
|
||||
}
|
||||
Ok(WebsocketResponse::Err { error }) if error.is_doc_not_found() => {
|
||||
self.events.push(SpaceSyncEvent::DocNotFound { doc_id });
|
||||
}
|
||||
Ok(WebsocketResponse::Err { error })
|
||||
if error.is_not_in_space() && !retried_not_in_space =>
|
||||
{
|
||||
self.joined_doc_ids.remove(&wire_doc_id);
|
||||
let _ = self.dispatch_load_doc(doc_id, state_vector, true, now_ms);
|
||||
}
|
||||
Ok(WebsocketResponse::Err { error }) if error.is_permission_revoked() => {
|
||||
let code = error.canonical_code().to_string();
|
||||
self.handle_auth_or_permission_pause(
|
||||
Some(doc_id),
|
||||
&code,
|
||||
error.message,
|
||||
None,
|
||||
now_ms,
|
||||
);
|
||||
}
|
||||
Ok(WebsocketResponse::Err { error }) => self.emit_request_failed(
|
||||
SPACE_LOAD_DOC,
|
||||
Some(doc_id),
|
||||
error.canonical_code().to_string(),
|
||||
error.message,
|
||||
),
|
||||
Err(err) => self.emit_request_failed(
|
||||
SPACE_LOAD_DOC,
|
||||
Some(doc_id),
|
||||
"INVALID_RESPONSE".into(),
|
||||
err.to_string(),
|
||||
),
|
||||
},
|
||||
InFlightRequest::PushDocUpdate {
|
||||
entry,
|
||||
wire_doc_id,
|
||||
retried_not_in_space,
|
||||
} => {
|
||||
match serde_json::from_value::<WebsocketResponse<PushDocUpdateResponse>>(payload) {
|
||||
Ok(WebsocketResponse::Ok { data }) => {
|
||||
self.offline_retry_attempts = 0;
|
||||
self.events.push(SpaceSyncEvent::DocUpdatePushed {
|
||||
doc_id: entry.doc_id,
|
||||
timestamp: data.timestamp,
|
||||
created: data.created,
|
||||
});
|
||||
}
|
||||
Ok(WebsocketResponse::Err { error })
|
||||
if error.is_not_in_space() && !retried_not_in_space =>
|
||||
{
|
||||
self.joined_doc_ids.remove(&wire_doc_id);
|
||||
let _ = self.dispatch_push_doc_update(entry, true, now_ms);
|
||||
}
|
||||
Ok(WebsocketResponse::Err { error }) if error.is_permission_revoked() => {
|
||||
let code = error.canonical_code().to_string();
|
||||
let doc_id = entry.doc_id.clone();
|
||||
self.handle_auth_or_permission_pause(
|
||||
Some(doc_id),
|
||||
&code,
|
||||
error.message,
|
||||
Some((ack_id, entry)),
|
||||
now_ms,
|
||||
);
|
||||
}
|
||||
Ok(WebsocketResponse::Err { error }) => {
|
||||
let doc_id = entry.doc_id.clone();
|
||||
self.shelve_push_for_retry(entry, now_ms);
|
||||
self.emit_request_failed(
|
||||
SPACE_PUSH_DOC_UPDATE,
|
||||
Some(doc_id),
|
||||
error.canonical_code().to_string(),
|
||||
error.message,
|
||||
);
|
||||
}
|
||||
Err(err) => {
|
||||
let doc_id = entry.doc_id.clone();
|
||||
self.shelve_push_for_retry(entry, now_ms);
|
||||
self.emit_request_failed(
|
||||
SPACE_PUSH_DOC_UPDATE,
|
||||
Some(doc_id),
|
||||
"INVALID_RESPONSE".into(),
|
||||
err.to_string(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
InFlightRequest::LoadDocTimestamps => {
|
||||
match serde_json::from_value::<WebsocketResponse<BTreeMap<String, i64>>>(payload) {
|
||||
Ok(WebsocketResponse::Ok { data }) => {
|
||||
let mut normalized = BTreeMap::new();
|
||||
for (wire_id, ts) in data {
|
||||
let local_id = self.id_converter.old_id_to_new_id(&wire_id);
|
||||
if self.id_converter.new_id_to_old_id(&local_id) == wire_id {
|
||||
normalized.insert(local_id, ts);
|
||||
}
|
||||
}
|
||||
self.events.push(SpaceSyncEvent::DocTimestampsLoaded {
|
||||
timestamps: normalized,
|
||||
});
|
||||
}
|
||||
Ok(WebsocketResponse::Err { error }) if error.is_permission_revoked() => {
|
||||
let code = error.canonical_code().to_string();
|
||||
self.handle_auth_or_permission_pause(
|
||||
None,
|
||||
&code,
|
||||
error.message,
|
||||
None,
|
||||
now_ms,
|
||||
);
|
||||
}
|
||||
Ok(WebsocketResponse::Err { error }) => self.emit_request_failed(
|
||||
SPACE_LOAD_DOC_TIMESTAMPS,
|
||||
None,
|
||||
error.canonical_code().to_string(),
|
||||
error.message,
|
||||
),
|
||||
Err(err) => self.emit_request_failed(
|
||||
SPACE_LOAD_DOC_TIMESTAMPS,
|
||||
None,
|
||||
"INVALID_RESPONSE".into(),
|
||||
err.to_string(),
|
||||
),
|
||||
}
|
||||
}
|
||||
InFlightRequest::DeleteDoc { doc_id } => {
|
||||
match serde_json::from_value::<WebsocketResponse<Value>>(payload) {
|
||||
Ok(WebsocketResponse::Ok { .. }) => {
|
||||
self.events.push(SpaceSyncEvent::DocDeleted { doc_id });
|
||||
}
|
||||
Ok(WebsocketResponse::Err { error }) if error.is_permission_revoked() => {
|
||||
let code = error.canonical_code().to_string();
|
||||
self.handle_auth_or_permission_pause(
|
||||
Some(doc_id),
|
||||
&code,
|
||||
error.message,
|
||||
None,
|
||||
now_ms,
|
||||
);
|
||||
}
|
||||
Ok(WebsocketResponse::Err { error }) => self.emit_request_failed(
|
||||
SPACE_DELETE_DOC,
|
||||
Some(doc_id),
|
||||
error.canonical_code().to_string(),
|
||||
error.message,
|
||||
),
|
||||
Err(err) => self.emit_request_failed(
|
||||
SPACE_DELETE_DOC,
|
||||
Some(doc_id),
|
||||
"INVALID_RESPONSE".into(),
|
||||
err.to_string(),
|
||||
),
|
||||
}
|
||||
}
|
||||
InFlightRequest::DocLifecycle { doc_id, lifecycle } => {
|
||||
match serde_json::from_value::<WebsocketResponse<DocLifecycleResponse>>(payload) {
|
||||
Ok(WebsocketResponse::Ok { data }) => {
|
||||
if lifecycle == DocLifecycleAction::Delete {
|
||||
self.pending_deletes.remove(&doc_id);
|
||||
}
|
||||
self.events.push(SpaceSyncEvent::DocLifecycleApplied {
|
||||
doc_id,
|
||||
lifecycle,
|
||||
timestamp: data.timestamp,
|
||||
deleted_doc_ids: data.deleted_doc_ids,
|
||||
});
|
||||
}
|
||||
Ok(WebsocketResponse::Err { error }) => {
|
||||
if lifecycle == DocLifecycleAction::Delete
|
||||
&& error.is_terminal_lifecycle_error()
|
||||
{
|
||||
self.pending_deletes.remove(&doc_id);
|
||||
}
|
||||
if error.is_permission_revoked() {
|
||||
let code = error.canonical_code().to_string();
|
||||
self.handle_auth_or_permission_pause(
|
||||
Some(doc_id),
|
||||
&code,
|
||||
error.message,
|
||||
None,
|
||||
now_ms,
|
||||
);
|
||||
} else {
|
||||
self.emit_request_failed(
|
||||
SPACE_DOC_LIFECYCLE,
|
||||
Some(doc_id),
|
||||
error.canonical_code().to_string(),
|
||||
error.message,
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(err) => self.emit_request_failed(
|
||||
SPACE_DOC_LIFECYCLE,
|
||||
Some(doc_id),
|
||||
"INVALID_RESPONSE".into(),
|
||||
err.to_string(),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,544 @@
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::{
|
||||
BroadcastDocInvalidationMessage, BroadcastDocUpdatesMessage, DeferredAfterJoin, EngineIoOutput,
|
||||
InFlightRequest, JoinSpaceBatchEntry, JoinSpaceBatchMessage, LoadDocMessage,
|
||||
OfflinePendingUpdate, PendingAck, PushDocIntent, PushDocUpdateMessage,
|
||||
SPACE_BROADCAST_DOC_INVALIDATION, SPACE_BROADCAST_DOC_UPDATES, SPACE_DELETE_DOC,
|
||||
SPACE_DOC_LIFECYCLE, SPACE_JOIN_BATCH, SPACE_LOAD_DOC, SPACE_LOAD_DOC_TIMESTAMPS,
|
||||
SPACE_PUSH_DOC_UPDATE, SocketIoEvent, SpaceSyncEngine, SpaceSyncEvent, SpaceSyncOutbound,
|
||||
SpaceSyncState,
|
||||
};
|
||||
use crate::error::StoreResult;
|
||||
|
||||
impl SpaceSyncEngine {
|
||||
pub(super) fn send_join_docs_batch(
|
||||
&mut self,
|
||||
wire_doc_ids: Vec<String>,
|
||||
deferred: Option<DeferredAfterJoin>,
|
||||
now_ms: i64,
|
||||
) -> StoreResult<u64> {
|
||||
let spaces = wire_doc_ids
|
||||
.iter()
|
||||
.map(|wire_id| JoinSpaceBatchEntry {
|
||||
space_type: self.config.space_type,
|
||||
space_id: self.config.space_id.clone(),
|
||||
doc_id: Some(wire_id.clone()),
|
||||
})
|
||||
.collect();
|
||||
let join = JoinSpaceBatchMessage {
|
||||
spaces,
|
||||
client_version: self.config.client_version.clone(),
|
||||
protocol_version: self.config.protocol_version,
|
||||
};
|
||||
let (ack_id, pkt) = self
|
||||
.socket_io
|
||||
.encode_event_with_ack(SPACE_JOIN_BATCH, serde_json::to_value(join)?)?;
|
||||
self.in_flight.insert(
|
||||
ack_id,
|
||||
PendingAck {
|
||||
sent_at_ms: now_ms,
|
||||
request: InFlightRequest::JoinDocs {
|
||||
wire_doc_ids,
|
||||
deferred,
|
||||
},
|
||||
},
|
||||
);
|
||||
self.engine_io.send_message(&pkt)?;
|
||||
self.flush_engine_io_outputs(now_ms);
|
||||
Ok(ack_id)
|
||||
}
|
||||
|
||||
pub(super) fn dispatch_load_doc(
|
||||
&mut self,
|
||||
doc_id: String,
|
||||
state_vector: Option<Vec<u8>>,
|
||||
retried_not_in_space: bool,
|
||||
now_ms: i64,
|
||||
) -> StoreResult<u64> {
|
||||
let wire_doc_id = self.id_converter.new_id_to_old_id(&doc_id);
|
||||
if !self.joined_doc_ids.contains(&wire_doc_id) {
|
||||
return self.send_join_docs_batch(
|
||||
vec![wire_doc_id],
|
||||
Some(DeferredAfterJoin::LoadDoc {
|
||||
doc_id,
|
||||
state_vector,
|
||||
retried_not_in_space,
|
||||
}),
|
||||
now_ms,
|
||||
);
|
||||
}
|
||||
let msg = LoadDocMessage {
|
||||
space_type: self.config.space_type,
|
||||
space_id: self.config.space_id.clone(),
|
||||
doc_id: wire_doc_id.clone(),
|
||||
state_vector: state_vector.as_deref().map(|sv| BASE64.encode(sv)),
|
||||
};
|
||||
let (ack_id, packet) = self
|
||||
.socket_io
|
||||
.encode_event_with_ack(SPACE_LOAD_DOC, serde_json::to_value(msg)?)?;
|
||||
self.in_flight.insert(
|
||||
ack_id,
|
||||
PendingAck {
|
||||
sent_at_ms: now_ms,
|
||||
request: InFlightRequest::LoadDoc {
|
||||
doc_id,
|
||||
wire_doc_id,
|
||||
state_vector,
|
||||
retried_not_in_space,
|
||||
},
|
||||
},
|
||||
);
|
||||
self.engine_io.send_message(&packet)?;
|
||||
self.flush_engine_io_outputs(now_ms);
|
||||
Ok(ack_id)
|
||||
}
|
||||
|
||||
pub(super) fn dispatch_push_doc_update(
|
||||
&mut self,
|
||||
entry: OfflinePendingUpdate,
|
||||
retried_not_in_space: bool,
|
||||
now_ms: i64,
|
||||
) -> StoreResult<()> {
|
||||
let wire_doc_id = self.id_converter.new_id_to_old_id(&entry.doc_id);
|
||||
let needs_join = (retried_not_in_space
|
||||
|| (self.config.protocol_version != 1 && entry.intent == PushDocIntent::Update))
|
||||
&& !self.joined_doc_ids.contains(&wire_doc_id);
|
||||
if needs_join {
|
||||
self.send_join_docs_batch(
|
||||
vec![wire_doc_id],
|
||||
Some(DeferredAfterJoin::PushDocUpdate {
|
||||
entry,
|
||||
retried_not_in_space,
|
||||
}),
|
||||
now_ms,
|
||||
)?;
|
||||
return Ok(());
|
||||
}
|
||||
let intent = if self.config.protocol_version == 1 {
|
||||
PushDocIntent::Create
|
||||
} else {
|
||||
entry.intent
|
||||
};
|
||||
let msg = PushDocUpdateMessage {
|
||||
space_type: self.config.space_type,
|
||||
space_id: self.config.space_id.clone(),
|
||||
doc_id: wire_doc_id.clone(),
|
||||
update: BASE64.encode(&entry.update),
|
||||
intent,
|
||||
};
|
||||
let (ack_id, pkt) = self
|
||||
.socket_io
|
||||
.encode_event_with_ack(SPACE_PUSH_DOC_UPDATE, serde_json::to_value(msg)?)?;
|
||||
self.in_flight.insert(
|
||||
ack_id,
|
||||
PendingAck {
|
||||
sent_at_ms: now_ms,
|
||||
request: InFlightRequest::PushDocUpdate {
|
||||
entry,
|
||||
wire_doc_id,
|
||||
retried_not_in_space,
|
||||
},
|
||||
},
|
||||
);
|
||||
self.engine_io.send_message(&pkt)?;
|
||||
self.flush_engine_io_outputs(now_ms);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn flush_engine_io_outputs(&mut self, now_ms: i64) {
|
||||
self.engine_io_outputs
|
||||
.extend(self.engine_io.drain_outputs());
|
||||
if self.flushing_engine_io {
|
||||
return;
|
||||
}
|
||||
self.flushing_engine_io = true;
|
||||
while let Some(output) = self.engine_io_outputs.pop_front() {
|
||||
match output {
|
||||
EngineIoOutput::Connected { sid, upgraded_ws } => {
|
||||
self.outbound
|
||||
.push(SpaceSyncOutbound::Transport(EngineIoOutput::Connected {
|
||||
sid,
|
||||
upgraded_ws,
|
||||
}));
|
||||
let auth_payload = self.config.auth_mode.to_connect_payload();
|
||||
if let Ok(connect_pkt) = self.socket_io.encode_connect(Some(auth_payload)) {
|
||||
let _ = self.engine_io.send_message(&connect_pkt);
|
||||
}
|
||||
}
|
||||
EngineIoOutput::Message(sio_raw) => {
|
||||
if let Ok(Some(ev)) = self.socket_io.on_text_packet(&sio_raw) {
|
||||
self.handle_socket_io_event(ev, now_ms);
|
||||
}
|
||||
}
|
||||
EngineIoOutput::BinaryMessage(bytes) => {
|
||||
if let Ok(Some(ev)) = self.socket_io.on_binary_attachment(bytes) {
|
||||
self.handle_socket_io_event(ev, now_ms);
|
||||
}
|
||||
}
|
||||
EngineIoOutput::Closed { reason } => {
|
||||
self.handle_disconnect(&reason, now_ms);
|
||||
}
|
||||
EngineIoOutput::HeartbeatTimeout => {
|
||||
self.handle_disconnect("heartbeat timeout", now_ms);
|
||||
}
|
||||
other => {
|
||||
self.outbound.push(SpaceSyncOutbound::Transport(other));
|
||||
}
|
||||
}
|
||||
self.engine_io_outputs
|
||||
.extend(self.engine_io.drain_outputs());
|
||||
}
|
||||
self.flushing_engine_io = false;
|
||||
}
|
||||
|
||||
fn handle_socket_io_event(&mut self, event: SocketIoEvent, now_ms: i64) {
|
||||
match event {
|
||||
SocketIoEvent::Connected { .. } => {
|
||||
self.state = SpaceSyncState::Joining;
|
||||
let root_wire_id = self.id_converter.new_id_to_old_id(&self.config.space_id);
|
||||
let join = JoinSpaceBatchMessage {
|
||||
spaces: vec![JoinSpaceBatchEntry {
|
||||
space_type: self.config.space_type,
|
||||
space_id: self.config.space_id.clone(),
|
||||
doc_id: Some(root_wire_id.clone()),
|
||||
}],
|
||||
client_version: self.config.client_version.clone(),
|
||||
protocol_version: self.config.protocol_version,
|
||||
};
|
||||
if let Ok(val) = serde_json::to_value(join)
|
||||
&& let Ok((ack_id, pkt)) =
|
||||
self.socket_io.encode_event_with_ack(SPACE_JOIN_BATCH, val)
|
||||
{
|
||||
self.in_flight.insert(
|
||||
ack_id,
|
||||
PendingAck {
|
||||
sent_at_ms: now_ms,
|
||||
request: InFlightRequest::InitialJoin { root_wire_id },
|
||||
},
|
||||
);
|
||||
if self.engine_io.send_message(&pkt).is_ok() {
|
||||
self.flush_engine_io_outputs(now_ms);
|
||||
}
|
||||
}
|
||||
}
|
||||
SocketIoEvent::ConnectError(err) => {
|
||||
self.requeue_in_flight_pushes(None);
|
||||
self.joined_doc_ids.clear();
|
||||
self.next_offline_retry_at_ms = None;
|
||||
self.waiting_for_id_converter = false;
|
||||
self.state = SpaceSyncState::AuthRequired;
|
||||
self.engine_io.disconnect();
|
||||
self.flush_engine_io_outputs(now_ms);
|
||||
self.events.push(SpaceSyncEvent::AuthRequired {
|
||||
doc_id: None,
|
||||
code: "CONNECT_ERROR".to_string(),
|
||||
message: err.to_string(),
|
||||
});
|
||||
}
|
||||
SocketIoEvent::Disconnected => {
|
||||
self.handle_disconnect("socket.io disconnect", now_ms);
|
||||
}
|
||||
SocketIoEvent::Event {
|
||||
event: name,
|
||||
payload,
|
||||
..
|
||||
} => {
|
||||
self.handle_server_event(&name, payload);
|
||||
}
|
||||
SocketIoEvent::Ack { ack_id, payload } => {
|
||||
self.handle_ack(ack_id, payload, now_ms);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_server_event(&mut self, name: &str, payload: Value) {
|
||||
match name {
|
||||
SPACE_BROADCAST_DOC_UPDATES => {
|
||||
if let Ok(msg) = serde_json::from_value::<BroadcastDocUpdatesMessage>(payload) {
|
||||
if msg.space_type != self.config.space_type
|
||||
|| msg.space_id != self.config.space_id
|
||||
{
|
||||
return;
|
||||
}
|
||||
let doc_id = self.id_converter.old_id_to_new_id(&msg.doc_id);
|
||||
if self.id_converter.new_id_to_old_id(&doc_id) != msg.doc_id {
|
||||
return;
|
||||
}
|
||||
let mut decoded = Vec::with_capacity(msg.updates.len());
|
||||
for encoded in msg.updates {
|
||||
if let Ok(bytes) = BASE64.decode(encoded) {
|
||||
decoded.push(bytes);
|
||||
}
|
||||
}
|
||||
self.events.push(SpaceSyncEvent::RemoteDocUpdates {
|
||||
doc_id,
|
||||
updates: decoded,
|
||||
timestamp: msg.timestamp,
|
||||
editor: msg.editor,
|
||||
});
|
||||
}
|
||||
}
|
||||
SPACE_BROADCAST_DOC_INVALIDATION => {
|
||||
if let Ok(msg) = serde_json::from_value::<BroadcastDocInvalidationMessage>(payload)
|
||||
{
|
||||
if msg.space_type != self.config.space_type
|
||||
|| msg.space_id != self.config.space_id
|
||||
{
|
||||
return;
|
||||
}
|
||||
self.events.push(SpaceSyncEvent::DocInvalidated {
|
||||
timestamp: msg.timestamp,
|
||||
inventory_changed: msg.inventory_changed.unwrap_or(false),
|
||||
});
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn handle_ack_timeout(
|
||||
&mut self,
|
||||
request: InFlightRequest,
|
||||
now_ms: i64,
|
||||
) -> StoreResult<()> {
|
||||
match request {
|
||||
InFlightRequest::PushDocUpdate { entry, .. } => {
|
||||
if self.state == SpaceSyncState::Ready {
|
||||
self.dispatch_push_doc_update(entry, false, now_ms)?;
|
||||
} else {
|
||||
self.offline_queue.push_front(entry);
|
||||
}
|
||||
}
|
||||
InFlightRequest::InitialJoin { .. } => {
|
||||
self.handle_disconnect("join ACK timeout", now_ms);
|
||||
}
|
||||
InFlightRequest::JoinDocs { deferred, .. } => {
|
||||
let doc_id = deferred_doc_id(deferred.as_ref());
|
||||
if let Some(DeferredAfterJoin::PushDocUpdate { entry, .. }) = deferred {
|
||||
self.shelve_push_for_retry(entry, now_ms);
|
||||
}
|
||||
self.emit_request_failed(
|
||||
SPACE_JOIN_BATCH,
|
||||
doc_id,
|
||||
"ACK_TIMEOUT".into(),
|
||||
"space:join-batch ACK timed out".into(),
|
||||
);
|
||||
}
|
||||
InFlightRequest::LoadDoc { doc_id, .. } => self.emit_request_failed(
|
||||
SPACE_LOAD_DOC,
|
||||
Some(doc_id),
|
||||
"ACK_TIMEOUT".into(),
|
||||
"space:load-doc ACK timed out".into(),
|
||||
),
|
||||
InFlightRequest::LoadDocTimestamps => self.emit_request_failed(
|
||||
SPACE_LOAD_DOC_TIMESTAMPS,
|
||||
None,
|
||||
"ACK_TIMEOUT".into(),
|
||||
"space:load-doc-timestamps ACK timed out".into(),
|
||||
),
|
||||
InFlightRequest::DeleteDoc { doc_id } => self.emit_request_failed(
|
||||
SPACE_DELETE_DOC,
|
||||
Some(doc_id),
|
||||
"ACK_TIMEOUT".into(),
|
||||
"space:delete-doc ACK timed out".into(),
|
||||
),
|
||||
InFlightRequest::DocLifecycle { doc_id, .. } => self.emit_request_failed(
|
||||
SPACE_DOC_LIFECYCLE,
|
||||
Some(doc_id),
|
||||
"ACK_TIMEOUT".into(),
|
||||
"space:doc-lifecycle ACK timed out".into(),
|
||||
),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn run_deferred_after_join(&mut self, op: DeferredAfterJoin, now_ms: i64) {
|
||||
match op {
|
||||
DeferredAfterJoin::LoadDoc {
|
||||
doc_id,
|
||||
state_vector,
|
||||
retried_not_in_space,
|
||||
} => {
|
||||
let _ = self.dispatch_load_doc(doc_id, state_vector, retried_not_in_space, now_ms);
|
||||
}
|
||||
DeferredAfterJoin::PushDocUpdate {
|
||||
entry,
|
||||
retried_not_in_space,
|
||||
} => {
|
||||
let _ = self.dispatch_push_doc_update(entry, retried_not_in_space, now_ms);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn emit_request_failed(
|
||||
&mut self,
|
||||
op: &'static str,
|
||||
doc_id: Option<String>,
|
||||
code: String,
|
||||
message: String,
|
||||
) {
|
||||
self.events.push(SpaceSyncEvent::RequestFailed {
|
||||
op,
|
||||
doc_id,
|
||||
code,
|
||||
message,
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn shelve_push_for_retry(&mut self, entry: OfflinePendingUpdate, now_ms: i64) {
|
||||
self.offline_queue.push_front(entry);
|
||||
if self.state == SpaceSyncState::Ready {
|
||||
let delay = self
|
||||
.config
|
||||
.reconnect
|
||||
.backoff_ms(self.offline_retry_attempts);
|
||||
self.offline_retry_attempts = self.offline_retry_attempts.saturating_add(1);
|
||||
let retry_at = now_ms.saturating_add(delay);
|
||||
self.next_offline_retry_at_ms = Some(retry_at);
|
||||
self.outbound
|
||||
.push(SpaceSyncOutbound::ScheduleTimerAtMs(retry_at));
|
||||
}
|
||||
}
|
||||
|
||||
/// Requeue all unacknowledged `PushDocUpdate` requests (and optional currently-failing entry)
|
||||
/// back to the front of `offline_queue` in their original ACK-ID order.
|
||||
pub(super) fn requeue_in_flight_pushes(
|
||||
&mut self,
|
||||
extra_failed: Option<(u64, OfflinePendingUpdate)>,
|
||||
) {
|
||||
let mut requeue: Vec<(u64, OfflinePendingUpdate)> = Vec::new();
|
||||
if let Some(extra) = extra_failed {
|
||||
requeue.push(extra);
|
||||
}
|
||||
for (ack_id, pending) in std::mem::take(&mut self.in_flight) {
|
||||
match pending.request {
|
||||
InFlightRequest::PushDocUpdate { entry, .. }
|
||||
| InFlightRequest::JoinDocs {
|
||||
deferred: Some(DeferredAfterJoin::PushDocUpdate { entry, .. }),
|
||||
..
|
||||
} => {
|
||||
requeue.push((ack_id, entry));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
requeue.sort_by_key(|(ack_id, _)| *ack_id);
|
||||
for (_, entry) in requeue.into_iter().rev() {
|
||||
self.offline_queue.push_front(entry);
|
||||
}
|
||||
}
|
||||
|
||||
/// Pause syncing on auth/permission error while preserving all unacknowledged and queued writes
|
||||
/// in `offline_queue` (isolated by `account_id`) so re-authentication never loses local data.
|
||||
pub(super) fn handle_auth_or_permission_pause(
|
||||
&mut self,
|
||||
doc_id: Option<String>,
|
||||
code: &str,
|
||||
message: String,
|
||||
failed_push: Option<(u64, OfflinePendingUpdate)>,
|
||||
now_ms: i64,
|
||||
) {
|
||||
let pauses_space = self.state == SpaceSyncState::Joining
|
||||
|| (doc_id.is_none() && code == "ACCESS_DENIED")
|
||||
|| matches!(
|
||||
code,
|
||||
"AUTHENTICATION_REQUIRED"
|
||||
| "FORBIDDEN"
|
||||
| "SPACE_ACCESS_DENIED"
|
||||
| "UNSUPPORTED_CLIENT_VERSION"
|
||||
);
|
||||
if pauses_space {
|
||||
self.requeue_in_flight_pushes(failed_push);
|
||||
self.joined_doc_ids.clear();
|
||||
self.next_offline_retry_at_ms = None;
|
||||
self.waiting_for_id_converter = false;
|
||||
self.state = if code == "AUTHENTICATION_REQUIRED" {
|
||||
SpaceSyncState::AuthRequired
|
||||
} else {
|
||||
SpaceSyncState::PermissionRevoked
|
||||
};
|
||||
self.engine_io.disconnect();
|
||||
self.flush_engine_io_outputs(now_ms);
|
||||
} else if let Some((_, entry)) = failed_push {
|
||||
// Quarantine doc-level rejected updates instead of re-queueing them into an infinite
|
||||
// retry loop on subsequent join_docs ACKs.
|
||||
self.rejected_updates.push(entry);
|
||||
}
|
||||
|
||||
if code == "AUTHENTICATION_REQUIRED" {
|
||||
self.events.push(SpaceSyncEvent::AuthRequired {
|
||||
doc_id,
|
||||
code: code.to_string(),
|
||||
message,
|
||||
});
|
||||
} else {
|
||||
self.events.push(SpaceSyncEvent::PermissionRevoked {
|
||||
doc_id,
|
||||
code: code.to_string(),
|
||||
message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Replay only queued writes belonging to the active `account_id`, keeping other accounts'
|
||||
/// writes isolated and frozen in `offline_queue`.
|
||||
pub(super) fn replay_offline_queue(&mut self, now_ms: i64) {
|
||||
let active_account = self.config.account_id.clone();
|
||||
let existing = std::mem::take(&mut self.offline_queue);
|
||||
let mut frozen_or_remaining = std::collections::VecDeque::new();
|
||||
let mut stopped = false;
|
||||
|
||||
for entry in existing {
|
||||
if stopped || entry.account_id != active_account {
|
||||
frozen_or_remaining.push_back(entry);
|
||||
continue;
|
||||
}
|
||||
if self
|
||||
.dispatch_push_doc_update(entry.clone(), false, now_ms)
|
||||
.is_err()
|
||||
{
|
||||
frozen_or_remaining.push_back(entry);
|
||||
stopped = true;
|
||||
}
|
||||
}
|
||||
self.offline_queue = frozen_or_remaining;
|
||||
}
|
||||
|
||||
pub(super) fn handle_disconnect(&mut self, reason: &str, now_ms: i64) {
|
||||
if matches!(
|
||||
self.state,
|
||||
SpaceSyncState::AuthRequired | SpaceSyncState::PermissionRevoked
|
||||
) {
|
||||
return;
|
||||
}
|
||||
self.joined_doc_ids.clear();
|
||||
self.next_offline_retry_at_ms = None;
|
||||
self.waiting_for_id_converter = false;
|
||||
self.requeue_in_flight_pushes(None);
|
||||
self.engine_io.disconnect();
|
||||
self.flush_engine_io_outputs(now_ms);
|
||||
|
||||
let delay = self.config.reconnect.backoff_ms(self.reconnect_attempts);
|
||||
self.reconnect_attempts = self.reconnect_attempts.saturating_add(1);
|
||||
let next_at = now_ms.saturating_add(delay);
|
||||
self.state = SpaceSyncState::ReconnectScheduled {
|
||||
next_attempt_at_ms: next_at,
|
||||
};
|
||||
self.outbound
|
||||
.push(SpaceSyncOutbound::ScheduleTimerAtMs(next_at));
|
||||
self.events.push(SpaceSyncEvent::Disconnected {
|
||||
reason: reason.to_string(),
|
||||
next_reconnect_ms: next_at,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn deferred_doc_id(deferred: Option<&DeferredAfterJoin>) -> Option<String> {
|
||||
match deferred {
|
||||
Some(DeferredAfterJoin::LoadDoc { doc_id, .. }) => Some(doc_id.clone()),
|
||||
Some(DeferredAfterJoin::PushDocUpdate { entry, .. }) => Some(entry.doc_id.clone()),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,839 @@
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::error::{StoreError, StoreResult};
|
||||
|
||||
/// Record separator used by Engine.IO v4 HTTP long-polling multi-packet payloads.
|
||||
pub const ENGINE_IO_RS: char = '\x1e';
|
||||
|
||||
/// Default timeout for initial `ConnectingPolling` / `ConnectingWebsocket` handshake.
|
||||
pub const DEFAULT_CONNECTING_TIMEOUT_MS: i64 = 15_000;
|
||||
|
||||
/// Transport selection mode matching `packages/common/nbstore/src/impls/cloud/socket.ts`.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum TransportMode {
|
||||
/// Self-hosted servers: start with HTTP long-polling and upgrade to WebSocket if offered.
|
||||
PollingThenWebsocket,
|
||||
/// Hosted cloud servers: connect directly over WebSocket.
|
||||
WebsocketOnly,
|
||||
}
|
||||
|
||||
/// Engine.IO v4 handshake JSON payload sent in the server's `0{...}` OPEN packet.
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EngineIoHandshake {
|
||||
pub sid: String,
|
||||
#[serde(default)]
|
||||
pub upgrades: Vec<String>,
|
||||
pub ping_interval: u64,
|
||||
pub ping_timeout: u64,
|
||||
#[serde(default)]
|
||||
pub max_payload: Option<usize>,
|
||||
}
|
||||
|
||||
/// Decoded Engine.IO v4 packet.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum EngineIoPacket {
|
||||
Open(EngineIoHandshake),
|
||||
Close,
|
||||
Ping(String),
|
||||
Pong(String),
|
||||
Message(String),
|
||||
Upgrade,
|
||||
Noop,
|
||||
Binary(Vec<u8>),
|
||||
}
|
||||
|
||||
impl EngineIoPacket {
|
||||
/// Encode a single Engine.IO v4 packet as a text frame (for polling or WebSocket text).
|
||||
pub fn encode_text(&self) -> StoreResult<String> {
|
||||
match self {
|
||||
Self::Open(handshake) => Ok(format!("0{}", serde_json::to_string(handshake)?)),
|
||||
Self::Close => Ok("1".to_string()),
|
||||
Self::Ping(payload) => Ok(format!("2{payload}")),
|
||||
Self::Pong(payload) => Ok(format!("3{payload}")),
|
||||
Self::Message(payload) => Ok(format!("4{payload}")),
|
||||
Self::Upgrade => Ok("5".to_string()),
|
||||
Self::Noop => Ok("6".to_string()),
|
||||
Self::Binary(bytes) => Ok(format!("b{}", BASE64.encode(bytes))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode a single Engine.IO v4 text packet.
|
||||
pub fn decode_text(raw: &str) -> StoreResult<Self> {
|
||||
let mut chars = raw.chars();
|
||||
let Some(tag) = chars.next() else {
|
||||
return Err(StoreError::InvalidProtocol("empty Engine.IO packet".into()));
|
||||
};
|
||||
let rest = chars.as_str();
|
||||
match tag {
|
||||
'0' => {
|
||||
let handshake: EngineIoHandshake = serde_json::from_str(rest)?;
|
||||
Ok(Self::Open(handshake))
|
||||
}
|
||||
'1' => Ok(Self::Close),
|
||||
'2' => Ok(Self::Ping(rest.to_string())),
|
||||
'3' => Ok(Self::Pong(rest.to_string())),
|
||||
'4' => Ok(Self::Message(rest.to_string())),
|
||||
'5' => Ok(Self::Upgrade),
|
||||
'6' => Ok(Self::Noop),
|
||||
'b' => {
|
||||
let bytes = BASE64
|
||||
.decode(rest)
|
||||
.map_err(|err| StoreError::InvalidProtocol(format!("invalid base64: {err}")))?;
|
||||
Ok(Self::Binary(bytes))
|
||||
}
|
||||
other => Err(StoreError::InvalidProtocol(format!(
|
||||
"unknown Engine.IO packet tag `{other}`"
|
||||
))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode multiple packets into an Engine.IO v4 HTTP long-polling payload separated by `\x1e`.
|
||||
pub fn encode_polling_payload(packets: &[EngineIoPacket]) -> StoreResult<String> {
|
||||
let mut encoded = Vec::with_capacity(packets.len());
|
||||
for packet in packets {
|
||||
encoded.push(packet.encode_text()?);
|
||||
}
|
||||
Ok(encoded.join(&ENGINE_IO_RS.to_string()))
|
||||
}
|
||||
|
||||
/// Decode an Engine.IO v4 HTTP long-polling payload separated by `\x1e`.
|
||||
pub fn decode_polling_payload(body: &str) -> StoreResult<Vec<EngineIoPacket>> {
|
||||
if body.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
body.split(ENGINE_IO_RS)
|
||||
.map(EngineIoPacket::decode_text)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Configuration for the sans-I/O Engine.IO v4 client.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct EngineIoConfig {
|
||||
pub transport_mode: TransportMode,
|
||||
}
|
||||
|
||||
/// Current lifecycle phase of [`EngineIoClient`].
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum EngineIoState {
|
||||
Disconnected,
|
||||
ConnectingPolling,
|
||||
PollingOpen,
|
||||
UpgradingToWebsocket,
|
||||
ConnectingWebsocket,
|
||||
WebsocketOpen,
|
||||
Closed,
|
||||
}
|
||||
|
||||
/// Side-effect outputs emitted by [`EngineIoClient`] for the host transport layer to execute.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum EngineIoOutput {
|
||||
SendPollingGet { sid: Option<String> },
|
||||
SendPollingPost { sid: String, body: String },
|
||||
OpenWebsocket { sid: Option<String> },
|
||||
SendWsText(String),
|
||||
SendWsBinary(Vec<u8>),
|
||||
CloseTransport,
|
||||
Connected { sid: String, upgraded_ws: bool },
|
||||
Message(String),
|
||||
BinaryMessage(Vec<u8>),
|
||||
Closed { reason: String },
|
||||
HeartbeatTimeout,
|
||||
}
|
||||
|
||||
/// Deterministic sans-I/O Engine.IO v4 client supporting serialized HTTP long-polling `POST`s,
|
||||
/// WebSocket probe/upgrade with full polling drain barrier, fallback to polling, and direct WS.
|
||||
pub struct EngineIoClient {
|
||||
config: EngineIoConfig,
|
||||
state: EngineIoState,
|
||||
sid: Option<String>,
|
||||
ping_interval_ms: i64,
|
||||
ping_timeout_ms: i64,
|
||||
last_server_activity_ms: i64,
|
||||
polling_get_in_flight: bool,
|
||||
polling_post_in_flight: bool,
|
||||
probe_verified: bool,
|
||||
pending_post_packets: Vec<EngineIoPacket>,
|
||||
outbound: Vec<EngineIoOutput>,
|
||||
}
|
||||
|
||||
impl EngineIoClient {
|
||||
pub fn new(config: EngineIoConfig) -> Self {
|
||||
Self {
|
||||
config,
|
||||
state: EngineIoState::Disconnected,
|
||||
sid: None,
|
||||
ping_interval_ms: 25_000,
|
||||
ping_timeout_ms: 20_000,
|
||||
last_server_activity_ms: 0,
|
||||
polling_get_in_flight: false,
|
||||
polling_post_in_flight: false,
|
||||
probe_verified: false,
|
||||
pending_post_packets: Vec::new(),
|
||||
outbound: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn state(&self) -> EngineIoState {
|
||||
self.state
|
||||
}
|
||||
|
||||
pub fn sid(&self) -> Option<&str> {
|
||||
self.sid.as_deref()
|
||||
}
|
||||
|
||||
pub fn is_polling_get_in_flight(&self) -> bool {
|
||||
self.polling_get_in_flight
|
||||
}
|
||||
|
||||
pub fn is_polling_post_in_flight(&self) -> bool {
|
||||
self.polling_post_in_flight
|
||||
}
|
||||
|
||||
pub fn is_probe_verified(&self) -> bool {
|
||||
self.probe_verified
|
||||
}
|
||||
|
||||
/// Initiate connection at deterministic timestamp `now_ms`.
|
||||
pub fn connect(&mut self, now_ms: i64) {
|
||||
self.sid = None;
|
||||
self.last_server_activity_ms = now_ms;
|
||||
self.polling_get_in_flight = false;
|
||||
self.polling_post_in_flight = false;
|
||||
self.probe_verified = false;
|
||||
self.pending_post_packets.clear();
|
||||
match self.config.transport_mode {
|
||||
TransportMode::PollingThenWebsocket => {
|
||||
self.state = EngineIoState::ConnectingPolling;
|
||||
self.polling_get_in_flight = true;
|
||||
self.outbound
|
||||
.push(EngineIoOutput::SendPollingGet { sid: None });
|
||||
}
|
||||
TransportMode::WebsocketOnly => {
|
||||
self.state = EngineIoState::ConnectingWebsocket;
|
||||
self.outbound
|
||||
.push(EngineIoOutput::OpenWebsocket { sid: None });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reset internal transport state and instruct the host to close active connections.
|
||||
pub fn disconnect(&mut self) {
|
||||
let was_active = !matches!(
|
||||
self.state,
|
||||
EngineIoState::Disconnected | EngineIoState::Closed
|
||||
);
|
||||
self.state = EngineIoState::Disconnected;
|
||||
self.sid = None;
|
||||
self.polling_get_in_flight = false;
|
||||
self.polling_post_in_flight = false;
|
||||
self.probe_verified = false;
|
||||
self.pending_post_packets.clear();
|
||||
if was_active {
|
||||
self.outbound.push(EngineIoOutput::CloseTransport);
|
||||
}
|
||||
}
|
||||
|
||||
/// Feed an HTTP polling GET response body received at `now_ms`.
|
||||
///
|
||||
/// Tolerates single corrupted frames inside a `\x1e`-delimited batch so valid sibling frames
|
||||
/// are still delivered.
|
||||
pub fn on_polling_response(&mut self, body: &str, now_ms: i64) -> StoreResult<()> {
|
||||
self.polling_get_in_flight = false;
|
||||
let mut saw_noop = false;
|
||||
if !body.is_empty() {
|
||||
for raw_frame in body.split(ENGINE_IO_RS) {
|
||||
let Ok(packet) = EngineIoPacket::decode_text(raw_frame) else {
|
||||
continue;
|
||||
};
|
||||
if matches!(packet, EngineIoPacket::Noop) {
|
||||
saw_noop = true;
|
||||
}
|
||||
self.handle_packet(packet, false, now_ms)?;
|
||||
}
|
||||
}
|
||||
|
||||
if self.state == EngineIoState::UpgradingToWebsocket && self.probe_verified {
|
||||
self.try_complete_ws_upgrade()?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if self.state == EngineIoState::PollingOpen
|
||||
|| (self.state == EngineIoState::UpgradingToWebsocket
|
||||
&& !saw_noop
|
||||
&& !self.probe_verified)
|
||||
{
|
||||
self.ensure_polling_get();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Notify the state machine that the in-flight HTTP polling `POST` completed.
|
||||
pub fn on_polling_post_complete(&mut self, _now_ms: i64) -> StoreResult<()> {
|
||||
self.polling_post_in_flight = false;
|
||||
if self.state == EngineIoState::UpgradingToWebsocket && self.probe_verified {
|
||||
self.try_complete_ws_upgrade()?;
|
||||
return Ok(());
|
||||
}
|
||||
if matches!(
|
||||
self.state,
|
||||
EngineIoState::PollingOpen | EngineIoState::UpgradingToWebsocket
|
||||
) {
|
||||
self.flush_pending_polling_post()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Notify the state machine that the in-flight HTTP polling `POST` failed.
|
||||
pub fn on_polling_post_error(&mut self, reason: &str, _now_ms: i64) {
|
||||
self.polling_post_in_flight = false;
|
||||
if self.state == EngineIoState::WebsocketOpen {
|
||||
return;
|
||||
}
|
||||
if matches!(
|
||||
self.state,
|
||||
EngineIoState::ConnectingPolling
|
||||
| EngineIoState::PollingOpen
|
||||
| EngineIoState::UpgradingToWebsocket
|
||||
) {
|
||||
self.state = EngineIoState::Closed;
|
||||
self.polling_get_in_flight = false;
|
||||
self.probe_verified = false;
|
||||
self.pending_post_packets.clear();
|
||||
self.outbound.push(EngineIoOutput::CloseTransport);
|
||||
self.outbound.push(EngineIoOutput::Closed {
|
||||
reason: reason.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Notify the state machine that the WebSocket transport is open (direct or upgrade).
|
||||
pub fn on_ws_open(&mut self, now_ms: i64) {
|
||||
self.last_server_activity_ms = now_ms;
|
||||
if self.state == EngineIoState::UpgradingToWebsocket {
|
||||
self.outbound
|
||||
.push(EngineIoOutput::SendWsText("2probe".to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Notify the state machine that the WebSocket transport failed or closed.
|
||||
///
|
||||
/// During `UpgradingToWebsocket`, the underlying HTTP long-polling session remains live
|
||||
/// on the server, so the client degrades smoothly back to `PollingOpen` instead of closing.
|
||||
pub fn on_ws_error(&mut self, reason: &str, now_ms: i64) {
|
||||
match self.state {
|
||||
EngineIoState::UpgradingToWebsocket => {
|
||||
self.last_server_activity_ms = now_ms;
|
||||
self.probe_verified = false;
|
||||
self.state = EngineIoState::PollingOpen;
|
||||
self.ensure_polling_get();
|
||||
let _ = self.flush_pending_polling_post();
|
||||
}
|
||||
EngineIoState::ConnectingWebsocket | EngineIoState::WebsocketOpen => {
|
||||
self.state = EngineIoState::Closed;
|
||||
self.polling_get_in_flight = false;
|
||||
self.polling_post_in_flight = false;
|
||||
self.probe_verified = false;
|
||||
self.pending_post_packets.clear();
|
||||
self.outbound.push(EngineIoOutput::CloseTransport);
|
||||
self.outbound.push(EngineIoOutput::Closed {
|
||||
reason: reason.to_string(),
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Feed an inbound WebSocket text frame received at `now_ms`.
|
||||
pub fn on_ws_text(&mut self, frame: &str, now_ms: i64) -> StoreResult<()> {
|
||||
let packet = EngineIoPacket::decode_text(frame)?;
|
||||
self.handle_packet(packet, true, now_ms)
|
||||
}
|
||||
|
||||
/// Feed an inbound WebSocket binary frame received at `now_ms`.
|
||||
pub fn on_ws_binary(&mut self, bytes: Vec<u8>, now_ms: i64) {
|
||||
self.last_server_activity_ms = now_ms;
|
||||
self.outbound.push(EngineIoOutput::BinaryMessage(bytes));
|
||||
}
|
||||
|
||||
/// Queue a Socket.IO text payload (`4...` Engine.IO message) over the active transport.
|
||||
pub fn send_message(&mut self, sio_payload: &str) -> StoreResult<()> {
|
||||
let packet = EngineIoPacket::Message(sio_payload.to_string());
|
||||
match self.state {
|
||||
EngineIoState::WebsocketOpen => {
|
||||
self.outbound
|
||||
.push(EngineIoOutput::SendWsText(packet.encode_text()?));
|
||||
Ok(())
|
||||
}
|
||||
EngineIoState::PollingOpen | EngineIoState::UpgradingToWebsocket => {
|
||||
self.enqueue_polling_packet(packet)
|
||||
}
|
||||
_ => Err(StoreError::InvalidProtocol(
|
||||
"cannot send message while Engine.IO is disconnected".into(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Check deterministic connecting timeout (15s) and heartbeat timeout at `now_ms`.
|
||||
pub fn poll_timeout(&mut self, now_ms: i64) -> bool {
|
||||
if matches!(
|
||||
self.state,
|
||||
EngineIoState::ConnectingPolling | EngineIoState::ConnectingWebsocket
|
||||
) {
|
||||
if now_ms.saturating_sub(self.last_server_activity_ms) >= DEFAULT_CONNECTING_TIMEOUT_MS
|
||||
{
|
||||
self.state = EngineIoState::Closed;
|
||||
self.polling_get_in_flight = false;
|
||||
self.polling_post_in_flight = false;
|
||||
self.probe_verified = false;
|
||||
self.pending_post_packets.clear();
|
||||
self.outbound.push(EngineIoOutput::CloseTransport);
|
||||
self.outbound.push(EngineIoOutput::Closed {
|
||||
reason: "connecting timeout".to_string(),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if !matches!(
|
||||
self.state,
|
||||
EngineIoState::PollingOpen
|
||||
| EngineIoState::UpgradingToWebsocket
|
||||
| EngineIoState::WebsocketOpen
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
let deadline = self.ping_interval_ms.saturating_add(self.ping_timeout_ms);
|
||||
if now_ms.saturating_sub(self.last_server_activity_ms) >= deadline {
|
||||
self.state = EngineIoState::Closed;
|
||||
self.polling_get_in_flight = false;
|
||||
self.polling_post_in_flight = false;
|
||||
self.probe_verified = false;
|
||||
self.pending_post_packets.clear();
|
||||
self.outbound.push(EngineIoOutput::CloseTransport);
|
||||
self.outbound.push(EngineIoOutput::HeartbeatTimeout);
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Drain all queued outputs in FIFO order.
|
||||
pub fn drain_outputs(&mut self) -> Vec<EngineIoOutput> {
|
||||
std::mem::take(&mut self.outbound)
|
||||
}
|
||||
|
||||
fn ensure_polling_get(&mut self) {
|
||||
if self.polling_get_in_flight || self.probe_verified {
|
||||
return;
|
||||
}
|
||||
if let Some(sid) = self.sid.clone() {
|
||||
self.polling_get_in_flight = true;
|
||||
self.outbound
|
||||
.push(EngineIoOutput::SendPollingGet { sid: Some(sid) });
|
||||
}
|
||||
}
|
||||
|
||||
fn enqueue_polling_packet(&mut self, packet: EngineIoPacket) -> StoreResult<()> {
|
||||
if self.sid.is_none() {
|
||||
return Err(StoreError::InvalidProtocol("missing Engine.IO sid".into()));
|
||||
}
|
||||
if self.probe_verified || self.polling_post_in_flight {
|
||||
self.pending_post_packets.push(packet);
|
||||
return Ok(());
|
||||
}
|
||||
self.pending_post_packets.push(packet);
|
||||
self.flush_pending_polling_post()
|
||||
}
|
||||
|
||||
fn flush_pending_polling_post(&mut self) -> StoreResult<()> {
|
||||
if self.polling_post_in_flight
|
||||
|| self.probe_verified
|
||||
|| self.pending_post_packets.is_empty()
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
let Some(sid) = self.sid.clone() else {
|
||||
return Err(StoreError::InvalidProtocol("missing Engine.IO sid".into()));
|
||||
};
|
||||
let batch = std::mem::take(&mut self.pending_post_packets);
|
||||
let body = encode_polling_payload(&batch)?;
|
||||
self.polling_post_in_flight = true;
|
||||
self.outbound
|
||||
.push(EngineIoOutput::SendPollingPost { sid, body });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn try_complete_ws_upgrade(&mut self) -> StoreResult<()> {
|
||||
if self.state != EngineIoState::UpgradingToWebsocket
|
||||
|| !self.probe_verified
|
||||
|| self.polling_get_in_flight
|
||||
|| self.polling_post_in_flight
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
self.state = EngineIoState::WebsocketOpen;
|
||||
self.probe_verified = false;
|
||||
self.outbound
|
||||
.push(EngineIoOutput::SendWsText("5".to_string()));
|
||||
for packet in std::mem::take(&mut self.pending_post_packets) {
|
||||
match packet {
|
||||
EngineIoPacket::Binary(bytes) => {
|
||||
self.outbound.push(EngineIoOutput::SendWsBinary(bytes));
|
||||
}
|
||||
other => {
|
||||
self.outbound
|
||||
.push(EngineIoOutput::SendWsText(other.encode_text()?));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_packet(
|
||||
&mut self,
|
||||
packet: EngineIoPacket,
|
||||
from_ws: bool,
|
||||
now_ms: i64,
|
||||
) -> StoreResult<()> {
|
||||
self.last_server_activity_ms = now_ms;
|
||||
match packet {
|
||||
EngineIoPacket::Open(handshake) => {
|
||||
self.sid = Some(handshake.sid.clone());
|
||||
self.ping_interval_ms = handshake.ping_interval as i64;
|
||||
self.ping_timeout_ms = handshake.ping_timeout as i64;
|
||||
let can_upgrade_ws = handshake
|
||||
.upgrades
|
||||
.iter()
|
||||
.any(|u| u.eq_ignore_ascii_case("websocket"));
|
||||
|
||||
if from_ws {
|
||||
self.state = EngineIoState::WebsocketOpen;
|
||||
self.outbound.push(EngineIoOutput::Connected {
|
||||
sid: handshake.sid,
|
||||
upgraded_ws: true,
|
||||
});
|
||||
} else if can_upgrade_ws
|
||||
&& self.config.transport_mode == TransportMode::PollingThenWebsocket
|
||||
{
|
||||
self.state = EngineIoState::UpgradingToWebsocket;
|
||||
self.outbound.push(EngineIoOutput::Connected {
|
||||
sid: handshake.sid.clone(),
|
||||
upgraded_ws: false,
|
||||
});
|
||||
self.outbound.push(EngineIoOutput::OpenWebsocket {
|
||||
sid: Some(handshake.sid),
|
||||
});
|
||||
} else {
|
||||
self.state = EngineIoState::PollingOpen;
|
||||
self.outbound.push(EngineIoOutput::Connected {
|
||||
sid: handshake.sid,
|
||||
upgraded_ws: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
EngineIoPacket::Ping(payload) => {
|
||||
let pong = EngineIoPacket::Pong(payload);
|
||||
if from_ws || self.state == EngineIoState::WebsocketOpen {
|
||||
self.outbound
|
||||
.push(EngineIoOutput::SendWsText(pong.encode_text()?));
|
||||
} else if self.sid.is_some() {
|
||||
self.enqueue_polling_packet(pong)?;
|
||||
}
|
||||
}
|
||||
EngineIoPacket::Pong(payload) => {
|
||||
if from_ws
|
||||
&& payload == "probe"
|
||||
&& self.state == EngineIoState::UpgradingToWebsocket
|
||||
{
|
||||
self.probe_verified = true;
|
||||
self.try_complete_ws_upgrade()?;
|
||||
}
|
||||
}
|
||||
EngineIoPacket::Message(msg) => {
|
||||
self.outbound.push(EngineIoOutput::Message(msg));
|
||||
}
|
||||
EngineIoPacket::Binary(bytes) => {
|
||||
self.outbound.push(EngineIoOutput::BinaryMessage(bytes));
|
||||
}
|
||||
EngineIoPacket::Close => {
|
||||
// Node Engine.IO v4 servers emit a Close ("1") on the stale long-polling GET
|
||||
// during or right after WebSocket upgrade; ignore it once WS probe succeeded.
|
||||
if !from_ws && (self.state == EngineIoState::WebsocketOpen || self.probe_verified) {
|
||||
return Ok(());
|
||||
}
|
||||
self.state = EngineIoState::Closed;
|
||||
self.polling_get_in_flight = false;
|
||||
self.polling_post_in_flight = false;
|
||||
self.probe_verified = false;
|
||||
self.pending_post_packets.clear();
|
||||
self.outbound.push(EngineIoOutput::CloseTransport);
|
||||
self.outbound.push(EngineIoOutput::Closed {
|
||||
reason: "server close".to_string(),
|
||||
});
|
||||
}
|
||||
EngineIoPacket::Upgrade | EngineIoPacket::Noop => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn polling_to_websocket_upgrade_and_heartbeat_timeout() {
|
||||
let mut client = EngineIoClient::new(EngineIoConfig {
|
||||
transport_mode: TransportMode::PollingThenWebsocket,
|
||||
});
|
||||
client.connect(1_000);
|
||||
assert_eq!(
|
||||
client.drain_outputs(),
|
||||
vec![EngineIoOutput::SendPollingGet { sid: None }]
|
||||
);
|
||||
|
||||
let open =
|
||||
r#"0{"sid":"s1","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":20000}"#;
|
||||
client.on_polling_response(open, 1_100).unwrap();
|
||||
assert_eq!(client.state(), EngineIoState::UpgradingToWebsocket);
|
||||
assert!(client.is_polling_get_in_flight());
|
||||
assert_eq!(
|
||||
client.drain_outputs(),
|
||||
vec![
|
||||
EngineIoOutput::Connected {
|
||||
sid: "s1".into(),
|
||||
upgraded_ws: false,
|
||||
},
|
||||
EngineIoOutput::OpenWebsocket {
|
||||
sid: Some("s1".into()),
|
||||
},
|
||||
EngineIoOutput::SendPollingGet {
|
||||
sid: Some("s1".into()),
|
||||
},
|
||||
]
|
||||
);
|
||||
|
||||
client.on_ws_open(1_200);
|
||||
assert_eq!(
|
||||
client.drain_outputs(),
|
||||
vec![EngineIoOutput::SendWsText("2probe".into())]
|
||||
);
|
||||
|
||||
// Server wakes in-flight polling GET with noop ("6") during probe without re-polling.
|
||||
client.on_polling_response("6", 1_250).unwrap();
|
||||
assert!(!client.is_polling_get_in_flight());
|
||||
assert!(client.drain_outputs().is_empty());
|
||||
|
||||
client.on_ws_text("3probe", 1_300).unwrap();
|
||||
assert_eq!(client.state(), EngineIoState::WebsocketOpen);
|
||||
assert_eq!(
|
||||
client.drain_outputs(),
|
||||
vec![EngineIoOutput::SendWsText("5".into())]
|
||||
);
|
||||
|
||||
// Server ping answered with pong.
|
||||
client.on_ws_text("2", 26_300).unwrap();
|
||||
assert_eq!(
|
||||
client.drain_outputs(),
|
||||
vec![EngineIoOutput::SendWsText("3".into())]
|
||||
);
|
||||
|
||||
// Not timed out yet at +44_999 ms, timed out at +45_000 ms.
|
||||
assert!(!client.poll_timeout(26_300 + 44_999));
|
||||
assert!(client.poll_timeout(26_300 + 45_000));
|
||||
assert_eq!(client.state(), EngineIoState::Closed);
|
||||
assert_eq!(
|
||||
client.drain_outputs(),
|
||||
vec![
|
||||
EngineIoOutput::CloseTransport,
|
||||
EngineIoOutput::HeartbeatTimeout,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polling_post_serializes_batches_and_waits_for_ws_upgrade_drain_barrier() {
|
||||
let mut client = EngineIoClient::new(EngineIoConfig {
|
||||
transport_mode: TransportMode::PollingThenWebsocket,
|
||||
});
|
||||
client.connect(1_000);
|
||||
let _ = client.drain_outputs();
|
||||
let open =
|
||||
r#"0{"sid":"s-ser","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":20000}"#;
|
||||
client.on_polling_response(open, 1_050).unwrap();
|
||||
let _ = client.drain_outputs();
|
||||
client.on_ws_open(1_100);
|
||||
let _ = client.drain_outputs();
|
||||
|
||||
// First message starts the single in-flight HTTP POST.
|
||||
client.send_message("0{}").unwrap();
|
||||
assert!(client.is_polling_post_in_flight());
|
||||
assert_eq!(
|
||||
client.drain_outputs(),
|
||||
vec![EngineIoOutput::SendPollingPost {
|
||||
sid: "s-ser".into(),
|
||||
body: "40{}".into(),
|
||||
}]
|
||||
);
|
||||
|
||||
// Interleave a polling Ping + two business messages while the first POST is still in flight.
|
||||
// None may start a concurrent POST!
|
||||
client.on_polling_response("2\x1e?corrupt", 1_150).unwrap();
|
||||
client.send_message(r#"2["m1"]"#).unwrap();
|
||||
client.send_message(r#"2["m2"]"#).unwrap();
|
||||
let interleaved_out = client.drain_outputs();
|
||||
assert!(
|
||||
!interleaved_out
|
||||
.iter()
|
||||
.any(|o| matches!(o, EngineIoOutput::SendPollingPost { .. })),
|
||||
"at most 1 polling POST may be in flight at once"
|
||||
);
|
||||
|
||||
// Completing the first POST flushes queued Pong + m1 + m2 in one \x1e-batched POST.
|
||||
client.on_polling_post_complete(1_200).unwrap();
|
||||
assert!(client.is_polling_post_in_flight());
|
||||
assert_eq!(
|
||||
client.drain_outputs(),
|
||||
vec![EngineIoOutput::SendPollingPost {
|
||||
sid: "s-ser".into(),
|
||||
body: "3\x1e42[\"m1\"]\x1e42[\"m2\"]".into(),
|
||||
}]
|
||||
);
|
||||
|
||||
// 3probe arrives while both polling GET and POST are still in flight:
|
||||
// must hold "5" and hold new message m3 until both drain!
|
||||
client.on_ws_text("3probe", 1_250).unwrap();
|
||||
assert_eq!(client.state(), EngineIoState::UpgradingToWebsocket);
|
||||
assert!(client.is_probe_verified());
|
||||
client.send_message(r#"2["m3"]"#).unwrap();
|
||||
assert!(client.drain_outputs().is_empty());
|
||||
|
||||
// Old polling GET returns "1" (Close) during drain -> must NOT close, still waiting on POST.
|
||||
client.on_polling_response("1", 1_300).unwrap();
|
||||
assert_eq!(client.state(), EngineIoState::UpgradingToWebsocket);
|
||||
assert!(!client.is_polling_get_in_flight());
|
||||
assert!(client.drain_outputs().is_empty());
|
||||
|
||||
// Completing the in-flight POST releases the drain barrier: sends "5" then m3 in FIFO order!
|
||||
client.on_polling_post_complete(1_350).unwrap();
|
||||
assert_eq!(client.state(), EngineIoState::WebsocketOpen);
|
||||
assert_eq!(
|
||||
client.drain_outputs(),
|
||||
vec![
|
||||
EngineIoOutput::SendWsText("5".into()),
|
||||
EngineIoOutput::SendWsText(r#"42["m3"]"#.into()),
|
||||
]
|
||||
);
|
||||
|
||||
// Even a late stale polling Close ("1") after WebsocketOpen is ignored.
|
||||
client.on_polling_response("1", 1_400).unwrap();
|
||||
assert_eq!(client.state(), EngineIoState::WebsocketOpen);
|
||||
assert!(client.drain_outputs().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_before_server_noop_and_late_polling_close_stays_websocket_open() {
|
||||
let mut client = EngineIoClient::new(EngineIoConfig {
|
||||
transport_mode: TransportMode::PollingThenWebsocket,
|
||||
});
|
||||
client.connect(1_000);
|
||||
let _ = client.drain_outputs();
|
||||
let open = r#"0{"sid":"s-race","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":20000}"#;
|
||||
client.on_polling_response(open, 1_050).unwrap();
|
||||
let _ = client.drain_outputs();
|
||||
client.on_ws_open(1_100);
|
||||
let _ = client.drain_outputs();
|
||||
|
||||
// 3probe arrives before server's 100ms noop while polling GET is in flight.
|
||||
assert!(client.is_polling_get_in_flight());
|
||||
client.on_ws_text("3probe", 1_120).unwrap();
|
||||
assert_eq!(client.state(), EngineIoState::UpgradingToWebsocket);
|
||||
assert!(client.drain_outputs().is_empty());
|
||||
|
||||
// Old polling GET returns "1" (Close) instead of noop -> transitions cleanly to WebsocketOpen.
|
||||
client.on_polling_response("1", 1_220).unwrap();
|
||||
assert_eq!(client.state(), EngineIoState::WebsocketOpen);
|
||||
assert_eq!(
|
||||
client.drain_outputs(),
|
||||
vec![EngineIoOutput::SendWsText("5".into())]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connecting_timeout_closes_stalled_handshake_after_15s() {
|
||||
let mut client = EngineIoClient::new(EngineIoConfig {
|
||||
transport_mode: TransportMode::WebsocketOnly,
|
||||
});
|
||||
client.connect(5_000);
|
||||
let _ = client.drain_outputs();
|
||||
assert!(!client.poll_timeout(5_000 + 14_999));
|
||||
assert!(client.poll_timeout(5_000 + 15_000));
|
||||
assert_eq!(client.state(), EngineIoState::Closed);
|
||||
assert_eq!(
|
||||
client.drain_outputs(),
|
||||
vec![
|
||||
EngineIoOutput::CloseTransport,
|
||||
EngineIoOutput::Closed {
|
||||
reason: "connecting timeout".into(),
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polling_loop_continues_and_ws_upgrade_failure_degrades_to_polling() {
|
||||
let mut client = EngineIoClient::new(EngineIoConfig {
|
||||
transport_mode: TransportMode::PollingThenWebsocket,
|
||||
});
|
||||
client.connect(1_000);
|
||||
let _ = client.drain_outputs();
|
||||
|
||||
let open =
|
||||
r#"0{"sid":"s2","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":20000}"#;
|
||||
client.on_polling_response(open, 1_050).unwrap();
|
||||
let _ = client.drain_outputs();
|
||||
|
||||
// Simulate reverse proxy blocking WS upgrade after noop cleared the in-flight GET.
|
||||
client.on_polling_response("6", 1_100).unwrap();
|
||||
assert!(!client.is_polling_get_in_flight());
|
||||
|
||||
client.on_ws_error("403 upgrade blocked", 1_200);
|
||||
assert_eq!(client.state(), EngineIoState::PollingOpen);
|
||||
assert!(client.is_polling_get_in_flight());
|
||||
assert_eq!(
|
||||
client.drain_outputs(),
|
||||
vec![EngineIoOutput::SendPollingGet {
|
||||
sid: Some("s2".into()),
|
||||
}]
|
||||
);
|
||||
|
||||
// Subsequent polling response delivers message and keeps the GET loop running.
|
||||
client
|
||||
.on_polling_response(r#"40{"sid":"sio-1"}"#, 1_300)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
client.drain_outputs(),
|
||||
vec![
|
||||
EngineIoOutput::Message(r#"0{"sid":"sio-1"}"#.into()),
|
||||
EngineIoOutput::SendPollingGet {
|
||||
sid: Some("s2".into()),
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polling_multi_packet_roundtrip_and_binary() {
|
||||
let packets = vec![
|
||||
EngineIoPacket::Ping(String::new()),
|
||||
EngineIoPacket::Message("40{\"sid\":\"sock\"}".into()),
|
||||
EngineIoPacket::Binary(vec![1, 2, 3, 4]),
|
||||
EngineIoPacket::Noop,
|
||||
];
|
||||
let encoded = encode_polling_payload(&packets).unwrap();
|
||||
let decoded = decode_polling_payload(&encoded).unwrap();
|
||||
assert_eq!(decoded, packets);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
pub mod engine;
|
||||
pub mod engine_io;
|
||||
pub mod protocol;
|
||||
pub mod socket_io;
|
||||
|
||||
pub use engine::{
|
||||
OfflinePendingUpdate, ReconnectPolicy, SocketAuthMode, SpaceSyncConfig, SpaceSyncEngine,
|
||||
SpaceSyncEvent, SpaceSyncOutbound, SpaceSyncState, SyncEngineSnapshot,
|
||||
};
|
||||
pub use engine_io::{
|
||||
DEFAULT_CONNECTING_TIMEOUT_MS, ENGINE_IO_RS, EngineIoClient, EngineIoConfig, EngineIoHandshake,
|
||||
EngineIoOutput, EngineIoPacket, EngineIoState, TransportMode, decode_polling_payload,
|
||||
encode_polling_payload,
|
||||
};
|
||||
pub use protocol::{
|
||||
BroadcastDocInvalidationMessage, BroadcastDocUpdatesMessage, DEFAULT_CLIENT_VERSION,
|
||||
DeleteDocMessage, DocLifecycleAction, DocLifecycleMessage, DocLifecycleResponse,
|
||||
JoinSpaceBatchEntry, JoinSpaceBatchMessage, JoinSpaceBatchResponse, LeaveSpaceBatchMessage,
|
||||
LoadDocMessage, LoadDocResponse, LoadDocTimestampsMessage, PushDocIntent, PushDocUpdateMessage,
|
||||
PushDocUpdateResponse, SPACE_BROADCAST_DOC_INVALIDATION, SPACE_BROADCAST_DOC_UPDATES,
|
||||
SPACE_DELETE_DOC, SPACE_DOC_LIFECYCLE, SPACE_JOIN_BATCH, SPACE_JOIN_BATCH_LIMIT,
|
||||
SPACE_LEAVE_BATCH, SPACE_LOAD_DOC, SPACE_LOAD_DOC_TIMESTAMPS, SPACE_LOAD_WORKSPACE_STATE,
|
||||
SPACE_PUSH_DOC_UPDATE, SpaceType, WebsocketErrorBody, WebsocketResponse,
|
||||
};
|
||||
pub use socket_io::{SocketIoClient, SocketIoEvent, SocketIoPacket};
|
||||
@@ -0,0 +1,302 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
pub const DEFAULT_CLIENT_VERSION: &str = "0.27.5";
|
||||
pub const SPACE_JOIN_BATCH_LIMIT: usize = 100;
|
||||
|
||||
// Client -> Server events (frozen v0.27.5 contract)
|
||||
pub const SPACE_JOIN_BATCH: &str = "space:join-batch";
|
||||
pub const SPACE_LEAVE_BATCH: &str = "space:leave-batch";
|
||||
pub const SPACE_LOAD_DOC: &str = "space:load-doc";
|
||||
pub const SPACE_PUSH_DOC_UPDATE: &str = "space:push-doc-update";
|
||||
pub const SPACE_LOAD_DOC_TIMESTAMPS: &str = "space:load-doc-timestamps";
|
||||
pub const SPACE_LOAD_WORKSPACE_STATE: &str = "space:load-workspace-state";
|
||||
pub const SPACE_DELETE_DOC: &str = "space:delete-doc";
|
||||
pub const SPACE_DOC_LIFECYCLE: &str = "space:doc-lifecycle";
|
||||
|
||||
// Server -> Client events (frozen v0.27.5 contract)
|
||||
pub const SPACE_BROADCAST_DOC_UPDATES: &str = "space:broadcast-doc-updates";
|
||||
pub const SPACE_BROADCAST_DOC_INVALIDATION: &str = "space:broadcast-doc-invalidation";
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum SpaceType {
|
||||
Workspace,
|
||||
Userspace,
|
||||
}
|
||||
|
||||
impl SpaceType {
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Workspace => "workspace",
|
||||
Self::Userspace => "userspace",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct JoinSpaceBatchEntry {
|
||||
pub space_type: SpaceType,
|
||||
pub space_id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub doc_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct JoinSpaceBatchMessage {
|
||||
pub spaces: Vec<JoinSpaceBatchEntry>,
|
||||
pub client_version: String,
|
||||
pub protocol_version: u8,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct JoinSpaceBatchResponse {
|
||||
pub client_id: String,
|
||||
pub success: bool,
|
||||
pub protocol_version: u8,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub client_version: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LeaveSpaceBatchMessage {
|
||||
pub space_type: SpaceType,
|
||||
pub space_id: String,
|
||||
pub doc_ids: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum PushDocIntent {
|
||||
Create,
|
||||
Update,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PushDocUpdateMessage {
|
||||
pub space_type: SpaceType,
|
||||
pub space_id: String,
|
||||
pub doc_id: String,
|
||||
pub update: String,
|
||||
pub intent: PushDocIntent,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PushDocUpdateResponse {
|
||||
pub accepted: bool,
|
||||
pub timestamp: i64,
|
||||
#[serde(default)]
|
||||
pub created: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LoadDocMessage {
|
||||
pub space_type: SpaceType,
|
||||
pub space_id: String,
|
||||
pub doc_id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub state_vector: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LoadDocResponse {
|
||||
pub missing: String,
|
||||
pub state: String,
|
||||
pub timestamp: i64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LoadDocTimestampsMessage {
|
||||
pub space_type: SpaceType,
|
||||
pub space_id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub timestamp: Option<i64>,
|
||||
}
|
||||
|
||||
pub type LoadDocTimestampsResponse = BTreeMap<String, i64>;
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DeleteDocMessage {
|
||||
pub space_type: SpaceType,
|
||||
pub space_id: String,
|
||||
pub doc_id: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum DocLifecycleAction {
|
||||
Trash,
|
||||
Restore,
|
||||
Delete,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DocLifecycleMessage {
|
||||
pub space_type: SpaceType,
|
||||
pub space_id: String,
|
||||
pub doc_id: String,
|
||||
pub lifecycle: DocLifecycleAction,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub physical_doc_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DocLifecycleResponse {
|
||||
pub timestamp: i64,
|
||||
#[serde(default)]
|
||||
pub deleted_doc_ids: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BroadcastDocUpdatesMessage {
|
||||
pub space_type: SpaceType,
|
||||
pub space_id: String,
|
||||
pub doc_id: String,
|
||||
pub updates: Vec<String>,
|
||||
pub timestamp: i64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub editor: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub compressed: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BroadcastDocInvalidationMessage {
|
||||
pub space_type: SpaceType,
|
||||
pub space_id: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub timestamp: Option<i64>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub inventory_changed: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WebsocketErrorBody {
|
||||
#[serde(default)]
|
||||
pub status: Option<u16>,
|
||||
#[serde(default)]
|
||||
pub code: Option<String>,
|
||||
#[serde(default, rename = "type")]
|
||||
pub error_type: Option<String>,
|
||||
pub name: String,
|
||||
pub message: String,
|
||||
#[serde(default)]
|
||||
pub data: Option<Value>,
|
||||
}
|
||||
|
||||
impl WebsocketErrorBody {
|
||||
pub fn canonical_code(&self) -> &str {
|
||||
self.code.as_deref().unwrap_or(&self.name)
|
||||
}
|
||||
|
||||
pub fn is_auth_required(&self) -> bool {
|
||||
self.canonical_code() == "AUTHENTICATION_REQUIRED"
|
||||
}
|
||||
|
||||
pub fn is_permission_revoked(&self) -> bool {
|
||||
matches!(
|
||||
self.canonical_code(),
|
||||
"SPACE_ACCESS_DENIED"
|
||||
| "DOC_ACTION_DENIED"
|
||||
| "ACCESS_DENIED"
|
||||
| "FORBIDDEN"
|
||||
| "AUTHENTICATION_REQUIRED"
|
||||
| "UNSUPPORTED_CLIENT_VERSION"
|
||||
)
|
||||
}
|
||||
|
||||
pub fn is_doc_not_found(&self) -> bool {
|
||||
self.canonical_code() == "DOC_NOT_FOUND" || self.name == "DOC_NOT_FOUND"
|
||||
}
|
||||
|
||||
pub fn is_not_in_space(&self) -> bool {
|
||||
self.canonical_code() == "NOT_IN_SPACE" || self.name == "NOT_IN_SPACE"
|
||||
}
|
||||
|
||||
pub fn is_terminal_lifecycle_error(&self) -> bool {
|
||||
matches!(
|
||||
self.canonical_code(),
|
||||
"DOC_ACTION_DENIED" | "SPACE_ACCESS_DENIED" | "ACCESS_DENIED" | "BAD_REQUEST"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum WebsocketResponse<T> {
|
||||
Ok { data: T },
|
||||
Err { error: WebsocketErrorBody },
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn event_names_match_frozen_oracle_contracts() {
|
||||
let oracle_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../../tests/oracle-contracts/v0.27.5/socketio-events.json");
|
||||
let raw = std::fs::read_to_string(&oracle_path)
|
||||
.expect("tests/oracle-contracts/v0.27.5/socketio-events.json must exist");
|
||||
let json: Value = serde_json::from_str(&raw).unwrap();
|
||||
|
||||
let incoming: BTreeSet<String> = json["incoming"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|e| e["event"].as_str().map(str::to_string))
|
||||
.collect();
|
||||
let outgoing: BTreeSet<String> = json["outgoing"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|e| e["event"].as_str().map(str::to_string))
|
||||
.collect();
|
||||
|
||||
for client_event in [
|
||||
SPACE_JOIN_BATCH,
|
||||
SPACE_LEAVE_BATCH,
|
||||
SPACE_LOAD_DOC,
|
||||
SPACE_PUSH_DOC_UPDATE,
|
||||
SPACE_LOAD_DOC_TIMESTAMPS,
|
||||
SPACE_LOAD_WORKSPACE_STATE,
|
||||
SPACE_DELETE_DOC,
|
||||
SPACE_DOC_LIFECYCLE,
|
||||
] {
|
||||
assert!(
|
||||
incoming.contains(client_event),
|
||||
"missing client event `{client_event}` in frozen oracle contract"
|
||||
);
|
||||
}
|
||||
|
||||
for server_event in [
|
||||
SPACE_BROADCAST_DOC_UPDATES,
|
||||
SPACE_BROADCAST_DOC_INVALIDATION,
|
||||
] {
|
||||
assert!(
|
||||
outgoing.contains(server_event),
|
||||
"missing server event `{server_event}` in frozen oracle contract"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::error::{StoreError, StoreResult};
|
||||
|
||||
const MAX_BINARY_ATTACHMENTS: usize = 16;
|
||||
|
||||
/// Decoded Socket.IO v4 packet on the default `/` namespace.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum SocketIoPacket {
|
||||
Connect(Option<Value>),
|
||||
Disconnect,
|
||||
Event {
|
||||
ack_id: Option<u64>,
|
||||
event: String,
|
||||
payload: Value,
|
||||
},
|
||||
Ack {
|
||||
ack_id: u64,
|
||||
payload: Value,
|
||||
},
|
||||
ConnectError(Value),
|
||||
BinaryEventHeader {
|
||||
attachments: usize,
|
||||
ack_id: Option<u64>,
|
||||
event: String,
|
||||
payload: Value,
|
||||
},
|
||||
}
|
||||
|
||||
impl SocketIoPacket {
|
||||
/// Encode a Socket.IO v4 packet as the payload inside an Engine.IO `4` message frame.
|
||||
pub fn encode(&self) -> StoreResult<String> {
|
||||
match self {
|
||||
Self::Connect(None) => Ok("0".to_string()),
|
||||
Self::Connect(Some(auth)) => Ok(format!("0{}", serde_json::to_string(auth)?)),
|
||||
Self::Disconnect => Ok("1".to_string()),
|
||||
Self::Event {
|
||||
ack_id,
|
||||
event,
|
||||
payload,
|
||||
} => {
|
||||
let body = serde_json::to_string(&json!([event, payload]))?;
|
||||
match ack_id {
|
||||
Some(id) => Ok(format!("2{id}{body}")),
|
||||
None => Ok(format!("2{body}")),
|
||||
}
|
||||
}
|
||||
Self::Ack { ack_id, payload } => {
|
||||
let body = serde_json::to_string(&json!([payload]))?;
|
||||
Ok(format!("3{ack_id}{body}"))
|
||||
}
|
||||
Self::ConnectError(err) => Ok(format!("4{}", serde_json::to_string(err)?)),
|
||||
Self::BinaryEventHeader {
|
||||
attachments,
|
||||
ack_id,
|
||||
event,
|
||||
payload,
|
||||
} => {
|
||||
let body = serde_json::to_string(&json!([event, payload]))?;
|
||||
match ack_id {
|
||||
Some(id) => Ok(format!("5{attachments}-{id}{body}")),
|
||||
None => Ok(format!("5{attachments}-{body}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode a Socket.IO v4 packet (after stripping the outer Engine.IO `4` prefix).
|
||||
pub fn decode(raw: &str) -> StoreResult<Self> {
|
||||
let mut chars = raw.chars();
|
||||
let Some(tag) = chars.next() else {
|
||||
return Err(StoreError::InvalidProtocol("empty Socket.IO packet".into()));
|
||||
};
|
||||
let rest = chars.as_str();
|
||||
match tag {
|
||||
'0' => {
|
||||
if rest.is_empty() {
|
||||
Ok(Self::Connect(None))
|
||||
} else {
|
||||
Ok(Self::Connect(Some(serde_json::from_str(rest)?)))
|
||||
}
|
||||
}
|
||||
'1' => Ok(Self::Disconnect),
|
||||
'2' => {
|
||||
let (ack_id, arr) = parse_ack_and_json_array(rest)?;
|
||||
let event = arr
|
||||
.first()
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| StoreError::InvalidProtocol("missing event name".into()))?
|
||||
.to_string();
|
||||
let payload = arr.get(1).cloned().unwrap_or(Value::Null);
|
||||
Ok(Self::Event {
|
||||
ack_id,
|
||||
event,
|
||||
payload,
|
||||
})
|
||||
}
|
||||
'3' => {
|
||||
let (ack_id, arr) = parse_ack_and_json_array(rest)?;
|
||||
let ack_id = ack_id.ok_or_else(|| {
|
||||
StoreError::InvalidProtocol("Socket.IO ACK missing ack_id".into())
|
||||
})?;
|
||||
let payload = arr.into_iter().next().unwrap_or(Value::Null);
|
||||
Ok(Self::Ack { ack_id, payload })
|
||||
}
|
||||
'4' => Ok(Self::ConnectError(serde_json::from_str(rest)?)),
|
||||
'5' => {
|
||||
let (count_str, after_dash) = rest.split_once('-').ok_or_else(|| {
|
||||
StoreError::InvalidProtocol("BINARY_EVENT missing attachment separator".into())
|
||||
})?;
|
||||
let attachments: usize = count_str.parse().map_err(|_| {
|
||||
StoreError::InvalidProtocol("invalid BINARY_EVENT attachment count".into())
|
||||
})?;
|
||||
if attachments > MAX_BINARY_ATTACHMENTS {
|
||||
return Err(StoreError::InvalidProtocol(
|
||||
"BINARY_EVENT attachment count exceeds limit".into(),
|
||||
));
|
||||
}
|
||||
let (ack_id, arr) = parse_ack_and_json_array(after_dash)?;
|
||||
let event = arr
|
||||
.first()
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| {
|
||||
StoreError::InvalidProtocol("BINARY_EVENT missing event name".into())
|
||||
})?
|
||||
.to_string();
|
||||
let payload = arr.get(1).cloned().unwrap_or(Value::Null);
|
||||
Ok(Self::BinaryEventHeader {
|
||||
attachments,
|
||||
ack_id,
|
||||
event,
|
||||
payload,
|
||||
})
|
||||
}
|
||||
other => Err(StoreError::InvalidProtocol(format!(
|
||||
"unsupported Socket.IO packet type `{other}`"
|
||||
))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_ack_and_json_array(rest: &str) -> StoreResult<(Option<u64>, Vec<Value>)> {
|
||||
let bracket_idx = rest
|
||||
.find('[')
|
||||
.ok_or_else(|| StoreError::InvalidProtocol("Socket.IO packet missing JSON array".into()))?;
|
||||
let ack_id = if bracket_idx == 0 {
|
||||
None
|
||||
} else {
|
||||
Some(
|
||||
rest[..bracket_idx]
|
||||
.parse::<u64>()
|
||||
.map_err(|_| StoreError::InvalidProtocol("invalid Socket.IO ack_id".into()))?,
|
||||
)
|
||||
};
|
||||
let arr: Vec<Value> = serde_json::from_str(&rest[bracket_idx..])?;
|
||||
Ok((ack_id, arr))
|
||||
}
|
||||
|
||||
fn replace_binary_placeholders(
|
||||
value: &mut Value,
|
||||
attachments: &mut [Option<Vec<u8>>],
|
||||
) -> StoreResult<()> {
|
||||
match value {
|
||||
Value::Object(map) => {
|
||||
if map.get("_placeholder") == Some(&Value::Bool(true)) {
|
||||
let idx = map
|
||||
.get("num")
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|n| usize::try_from(n).ok())
|
||||
.ok_or_else(|| {
|
||||
StoreError::InvalidProtocol("invalid binary placeholder index".into())
|
||||
})?;
|
||||
let slot = attachments.get_mut(idx).ok_or_else(|| {
|
||||
StoreError::InvalidProtocol("binary placeholder index out of bounds".into())
|
||||
})?;
|
||||
let bytes = slot.take().ok_or_else(|| {
|
||||
StoreError::InvalidProtocol("duplicate binary placeholder reference".into())
|
||||
})?;
|
||||
*value = Value::String(BASE64.encode(bytes));
|
||||
return Ok(());
|
||||
}
|
||||
for v in map.values_mut() {
|
||||
replace_binary_placeholders(v, attachments)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Value::Array(arr) => {
|
||||
for item in arr.iter_mut() {
|
||||
replace_binary_placeholders(item, attachments)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
struct PendingBinary {
|
||||
expected: usize,
|
||||
ack_id: Option<u64>,
|
||||
event: String,
|
||||
payload: Value,
|
||||
attachments: Vec<Option<Vec<u8>>>,
|
||||
}
|
||||
|
||||
/// High-level events produced by [`SocketIoClient`].
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum SocketIoEvent {
|
||||
Connected {
|
||||
sid: Option<String>,
|
||||
},
|
||||
ConnectError(Value),
|
||||
Disconnected,
|
||||
Event {
|
||||
ack_id: Option<u64>,
|
||||
event: String,
|
||||
payload: Value,
|
||||
},
|
||||
Ack {
|
||||
ack_id: u64,
|
||||
payload: Value,
|
||||
},
|
||||
}
|
||||
|
||||
/// Sans-I/O Socket.IO v4 framer handling ACK ID allocation and `BINARY_EVENT` reassembly.
|
||||
#[derive(Default)]
|
||||
pub struct SocketIoClient {
|
||||
next_ack_id: u64,
|
||||
pending_binary: Option<PendingBinary>,
|
||||
}
|
||||
|
||||
impl SocketIoClient {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Allocate the next monotonic ACK identifier.
|
||||
pub fn allocate_ack_id(&mut self) -> u64 {
|
||||
let id = self.next_ack_id;
|
||||
self.next_ack_id = self.next_ack_id.saturating_add(1);
|
||||
id
|
||||
}
|
||||
|
||||
/// Build a Socket.IO `CONNECT` packet (`0` or `0{...}`).
|
||||
pub fn encode_connect(&self, auth: Option<Value>) -> StoreResult<String> {
|
||||
SocketIoPacket::Connect(auth).encode()
|
||||
}
|
||||
|
||||
/// Build a Socket.IO `EVENT` packet with an automatically allocated ACK ID.
|
||||
pub fn encode_event_with_ack(
|
||||
&mut self,
|
||||
event: &str,
|
||||
payload: Value,
|
||||
) -> StoreResult<(u64, String)> {
|
||||
let ack_id = self.allocate_ack_id();
|
||||
let encoded = SocketIoPacket::Event {
|
||||
ack_id: Some(ack_id),
|
||||
event: event.to_string(),
|
||||
payload,
|
||||
}
|
||||
.encode()?;
|
||||
Ok((ack_id, encoded))
|
||||
}
|
||||
|
||||
/// Build a fire-and-forget Socket.IO `EVENT` packet without an ACK ID.
|
||||
pub fn encode_event(&self, event: &str, payload: Value) -> StoreResult<String> {
|
||||
SocketIoPacket::Event {
|
||||
ack_id: None,
|
||||
event: event.to_string(),
|
||||
payload,
|
||||
}
|
||||
.encode()
|
||||
}
|
||||
|
||||
/// Feed an inbound Socket.IO text packet (from Engine.IO `Message`).
|
||||
pub fn on_text_packet(&mut self, raw: &str) -> StoreResult<Option<SocketIoEvent>> {
|
||||
match SocketIoPacket::decode(raw)? {
|
||||
SocketIoPacket::Connect(payload) => {
|
||||
let sid = payload
|
||||
.as_ref()
|
||||
.and_then(|v| v.get("sid"))
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string);
|
||||
Ok(Some(SocketIoEvent::Connected { sid }))
|
||||
}
|
||||
SocketIoPacket::Disconnect => {
|
||||
self.pending_binary = None;
|
||||
Ok(Some(SocketIoEvent::Disconnected))
|
||||
}
|
||||
SocketIoPacket::ConnectError(err) => Ok(Some(SocketIoEvent::ConnectError(err))),
|
||||
SocketIoPacket::Event {
|
||||
ack_id,
|
||||
event,
|
||||
payload,
|
||||
} => Ok(Some(SocketIoEvent::Event {
|
||||
ack_id,
|
||||
event,
|
||||
payload,
|
||||
})),
|
||||
SocketIoPacket::Ack { ack_id, payload } => {
|
||||
Ok(Some(SocketIoEvent::Ack { ack_id, payload }))
|
||||
}
|
||||
SocketIoPacket::BinaryEventHeader {
|
||||
attachments,
|
||||
ack_id,
|
||||
event,
|
||||
mut payload,
|
||||
} => {
|
||||
if attachments == 0 {
|
||||
replace_binary_placeholders(&mut payload, &mut [])?;
|
||||
return Ok(Some(SocketIoEvent::Event {
|
||||
ack_id,
|
||||
event,
|
||||
payload,
|
||||
}));
|
||||
}
|
||||
self.pending_binary = Some(PendingBinary {
|
||||
expected: attachments,
|
||||
ack_id,
|
||||
event,
|
||||
payload,
|
||||
attachments: Vec::with_capacity(attachments),
|
||||
});
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Feed an inbound binary attachment for an in-progress `BINARY_EVENT`.
|
||||
pub fn on_binary_attachment(&mut self, bytes: Vec<u8>) -> StoreResult<Option<SocketIoEvent>> {
|
||||
let Some(pending) = self.pending_binary.as_mut() else {
|
||||
return Err(StoreError::InvalidProtocol(
|
||||
"unexpected binary attachment without pending BINARY_EVENT".into(),
|
||||
));
|
||||
};
|
||||
pending.attachments.push(Some(bytes));
|
||||
if pending.attachments.len() < pending.expected {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut completed = self.pending_binary.take().expect("pending exists");
|
||||
replace_binary_placeholders(&mut completed.payload, &mut completed.attachments)?;
|
||||
if !completed.attachments.iter().all(Option::is_none) {
|
||||
return Err(StoreError::InvalidProtocol(
|
||||
"BINARY_EVENT had unreferenced attachment slots".into(),
|
||||
));
|
||||
}
|
||||
Ok(Some(SocketIoEvent::Event {
|
||||
ack_id: completed.ack_id,
|
||||
event: completed.event,
|
||||
payload: completed.payload,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn binary_event_placeholder_reassembly_and_ack_pairing() {
|
||||
let mut client = SocketIoClient::new();
|
||||
let (ack0, encoded) = client
|
||||
.encode_event_with_ack("space:load-doc", json!({"docId": "d1"}))
|
||||
.unwrap();
|
||||
assert_eq!(ack0, 0);
|
||||
assert_eq!(encoded, r#"20["space:load-doc",{"docId":"d1"}]"#);
|
||||
|
||||
let ack_ev = client
|
||||
.on_text_packet(r#"30[{"data":{"timestamp":42}}]"#)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
ack_ev,
|
||||
SocketIoEvent::Ack {
|
||||
ack_id: 0,
|
||||
payload: json!({"data": {"timestamp": 42}}),
|
||||
}
|
||||
);
|
||||
|
||||
let bin_header = r#"51-["space:broadcast-doc-updates",{"docId":"d1","updates":[{"_placeholder":true,"num":0}]}]"#;
|
||||
assert!(client.on_text_packet(bin_header).unwrap().is_none());
|
||||
|
||||
let assembled = client
|
||||
.on_binary_attachment(vec![0xde, 0xad, 0xbe, 0xef])
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
assembled,
|
||||
SocketIoEvent::Event {
|
||||
ack_id: None,
|
||||
event: "space:broadcast-doc-updates".into(),
|
||||
payload: json!({
|
||||
"docId": "d1",
|
||||
"updates": [BASE64.encode([0xde, 0xad, 0xbe, 0xef])]
|
||||
}),
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,463 @@
|
||||
pub mod root_doc;
|
||||
pub mod tables;
|
||||
|
||||
pub use root_doc::{
|
||||
CreatePageOutcome, PageIdSource, PageMetaEntry, RemoteRootApply, WorkspaceRootDoc,
|
||||
derive_page_id_for_op,
|
||||
};
|
||||
pub use tables::{
|
||||
DELETED_FLAG_KEY, DocCustomPropertyInfoRow, DocIntegrationRefRow, DocPropertiesRow,
|
||||
ExplorerIconRow, FavoriteRow, FolderRow, PinnedCollectionRow, SettingsRow,
|
||||
USERDATA_TABLE_NAMES, UserdataTableName, WORKSPACE_DB_TABLE_NAMES, WorkspaceDbTableName,
|
||||
YjsTableDoc,
|
||||
};
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde::Serialize;
|
||||
use serde_json::Value as JsonValue;
|
||||
|
||||
use crate::error::StoreResult;
|
||||
|
||||
/// Protocol version 1: creating a document writes both `meta.pages` and `spaces[pageId]` atomically.
|
||||
pub const WORKSPACE_SYNC_PROTOCOL_VERSION: u8 = 1;
|
||||
|
||||
/// Pending encoded v1 update produced by a local `WorkspaceDb` mutation, ready for host
|
||||
/// persistence and sync enqueueing.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct PendingDocUpdate {
|
||||
pub doc_id: String,
|
||||
pub update: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Authoritative writer for a single workspace's root document and its 8 metadata Yjs tables
|
||||
/// (5 `db$` workspace tables + 3 `userdata$` user tables).
|
||||
pub struct WorkspaceDb {
|
||||
space_id: String,
|
||||
user_id: String,
|
||||
client_id: u64,
|
||||
root: WorkspaceRootDoc,
|
||||
db_tables: BTreeMap<WorkspaceDbTableName, YjsTableDoc>,
|
||||
resolved_db_tables: BTreeSet<WorkspaceDbTableName>,
|
||||
userdata_tables: BTreeMap<UserdataTableName, YjsTableDoc>,
|
||||
pending_updates: Vec<PendingDocUpdate>,
|
||||
}
|
||||
|
||||
impl WorkspaceDb {
|
||||
/// Create a fresh in-memory workspace DB coordinator with an uninitialized root document.
|
||||
pub fn new(space_id: impl Into<String>, user_id: impl Into<String>, client_id: u64) -> Self {
|
||||
let space_id = space_id.into();
|
||||
let user_id = user_id.into();
|
||||
let root = WorkspaceRootDoc::new(space_id.clone(), client_id);
|
||||
Self {
|
||||
space_id,
|
||||
user_id,
|
||||
client_id,
|
||||
root,
|
||||
db_tables: BTreeMap::new(),
|
||||
resolved_db_tables: WORKSPACE_DB_TABLE_NAMES.iter().copied().collect(),
|
||||
userdata_tables: BTreeMap::new(),
|
||||
pending_updates: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Load an existing root document snapshot with zero writeback.
|
||||
///
|
||||
/// Companion `db$` tables start in the unresolved state until loaded via [`Self::load_db_table`]
|
||||
/// or explicitly confirmed absent in storage via [`Self::mark_db_table_absent`].
|
||||
pub fn from_root_update_v1(
|
||||
space_id: impl Into<String>,
|
||||
user_id: impl Into<String>,
|
||||
client_id: u64,
|
||||
root_update: &[u8],
|
||||
) -> StoreResult<Self> {
|
||||
let space_id = space_id.into();
|
||||
let user_id = user_id.into();
|
||||
let root = WorkspaceRootDoc::from_update_v1(space_id.clone(), client_id, root_update)?;
|
||||
Ok(Self {
|
||||
space_id,
|
||||
user_id,
|
||||
client_id,
|
||||
root,
|
||||
db_tables: BTreeMap::new(),
|
||||
resolved_db_tables: BTreeSet::new(),
|
||||
userdata_tables: BTreeMap::new(),
|
||||
pending_updates: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn space_id(&self) -> &str {
|
||||
&self.space_id
|
||||
}
|
||||
|
||||
pub fn user_id(&self) -> &str {
|
||||
&self.user_id
|
||||
}
|
||||
|
||||
pub fn root(&self) -> &WorkspaceRootDoc {
|
||||
&self.root
|
||||
}
|
||||
|
||||
/// Inspect pending local updates queued for persistence and remote sync.
|
||||
pub fn pending_updates(&self) -> &[PendingDocUpdate] {
|
||||
&self.pending_updates
|
||||
}
|
||||
|
||||
/// Drain all pending local updates in FIFO order for host persistence and sync enqueueing.
|
||||
pub fn drain_pending_updates(&mut self) -> Vec<PendingDocUpdate> {
|
||||
std::mem::take(&mut self.pending_updates)
|
||||
}
|
||||
|
||||
fn record_update(&mut self, doc_id: String, update: Vec<u8>) {
|
||||
if !update.is_empty() && update != [0, 0] {
|
||||
self.pending_updates
|
||||
.push(PendingDocUpdate { doc_id, update });
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply a remote update to the root document without enqueuing it in `pending_updates`.
|
||||
pub fn apply_remote_root_update(&mut self, bytes: &[u8]) -> StoreResult<RemoteRootApply> {
|
||||
self.root.apply_remote_update(bytes)
|
||||
}
|
||||
|
||||
/// Explicitly initialize `meta.pages = []` for a new local workspace and record the update.
|
||||
pub fn initialize_meta(&mut self) -> StoreResult<Option<Vec<u8>>> {
|
||||
let update = self.root.initialize_meta()?;
|
||||
if let Some(ref bytes) = update {
|
||||
self.record_update(self.space_id.clone(), bytes.clone());
|
||||
}
|
||||
Ok(update)
|
||||
}
|
||||
|
||||
/// Atomically create a page in the root doc and record any emitted update.
|
||||
pub fn create_page(
|
||||
&mut self,
|
||||
id_source: PageIdSource<'_>,
|
||||
title: &str,
|
||||
create_date_ms: i64,
|
||||
) -> StoreResult<CreatePageOutcome> {
|
||||
let outcome = self.root.create_page(id_source, title, create_date_ms)?;
|
||||
if let Some(ref bytes) = outcome.update {
|
||||
self.record_update(self.space_id.clone(), bytes.clone());
|
||||
}
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
/// Return `true` when `table` already contains an active or soft-deleted row entry for
|
||||
/// `primary_key` (used to distinguish "row was never persisted before crash" from "row exists
|
||||
/// and user later cleared or changed a field").
|
||||
pub fn has_db_row_entry(
|
||||
&self,
|
||||
table: WorkspaceDbTableName,
|
||||
primary_key: &str,
|
||||
) -> StoreResult<bool> {
|
||||
let Some(doc) = self.db_tables.get(&table) else {
|
||||
return Ok(false);
|
||||
};
|
||||
Ok(doc.get_raw_row(primary_key).is_some() || doc.is_soft_deleted(primary_key)?)
|
||||
}
|
||||
|
||||
/// Rename a page in the root doc and record any emitted update.
|
||||
pub fn rename_page(&mut self, page_id: &str, new_title: &str) -> StoreResult<Option<Vec<u8>>> {
|
||||
let update = self.root.rename_page(page_id, new_title)?;
|
||||
if let Some(ref bytes) = update {
|
||||
self.record_update(self.space_id.clone(), bytes.clone());
|
||||
}
|
||||
Ok(update)
|
||||
}
|
||||
|
||||
/// Soft-delete a page in the root doc and record any emitted update.
|
||||
pub fn trash_page(
|
||||
&mut self,
|
||||
page_id: &str,
|
||||
trash_date_ms: i64,
|
||||
) -> StoreResult<Option<Vec<u8>>> {
|
||||
let update = self.root.trash_page(page_id, trash_date_ms)?;
|
||||
if let Some(ref bytes) = update {
|
||||
self.record_update(self.space_id.clone(), bytes.clone());
|
||||
}
|
||||
Ok(update)
|
||||
}
|
||||
|
||||
/// Restore a trashed page in the root doc and record any emitted update.
|
||||
pub fn restore_page(&mut self, page_id: &str) -> StoreResult<Option<Vec<u8>>> {
|
||||
let update = self.root.restore_page(page_id)?;
|
||||
if let Some(ref bytes) = update {
|
||||
self.record_update(self.space_id.clone(), bytes.clone());
|
||||
}
|
||||
Ok(update)
|
||||
}
|
||||
|
||||
/// Return `true` when `table` has been loaded from storage, initialized in a fresh workspace,
|
||||
/// or explicitly confirmed absent via [`Self::mark_db_table_absent`].
|
||||
pub fn is_db_table_resolved(&self, table: WorkspaceDbTableName) -> bool {
|
||||
self.resolved_db_tables.contains(&table)
|
||||
}
|
||||
|
||||
/// Mark `table` as confirmed absent in local storage (e.g. `get_doc("db$docProperties")`
|
||||
/// returned `None`).
|
||||
pub fn mark_db_table_absent(&mut self, table: WorkspaceDbTableName) {
|
||||
self.resolved_db_tables.insert(table);
|
||||
}
|
||||
|
||||
/// Load or CRDT-merge a workspace `db$` table document from encoded v1 bytes.
|
||||
///
|
||||
/// If local writes occurred before the snapshot arrived, merges via CRDT `apply_update_v1`
|
||||
/// instead of overwriting and losing local mutations.
|
||||
pub fn load_db_table(&mut self, table: WorkspaceDbTableName, update: &[u8]) -> StoreResult<()> {
|
||||
if let Some(existing) = self.db_tables.get_mut(&table) {
|
||||
existing.apply_update_v1(update)?;
|
||||
} else {
|
||||
let doc = YjsTableDoc::from_update_v1(
|
||||
table.local_doc_id(),
|
||||
table.primary_key_field(),
|
||||
table.known_fields(),
|
||||
self.client_id,
|
||||
update,
|
||||
)?;
|
||||
self.db_tables.insert(table, doc);
|
||||
}
|
||||
self.resolved_db_tables.insert(table);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Load or CRDT-merge a `userdata$` table document from encoded v1 bytes.
|
||||
pub fn load_userdata_table(
|
||||
&mut self,
|
||||
table: UserdataTableName,
|
||||
update: &[u8],
|
||||
) -> StoreResult<()> {
|
||||
if let Some(existing) = self.userdata_tables.get_mut(&table) {
|
||||
existing.apply_update_v1(update)?;
|
||||
return Ok(());
|
||||
}
|
||||
let doc = YjsTableDoc::from_update_v1(
|
||||
table.local_doc_id(&self.user_id),
|
||||
table.primary_key_field(),
|
||||
table.known_fields(),
|
||||
self.client_id,
|
||||
update,
|
||||
)?;
|
||||
self.userdata_tables.insert(table, doc);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Upsert a row in a `db$` table and record the emitted update in `pending_updates`.
|
||||
pub fn upsert_db_row<T: Serialize>(
|
||||
&mut self,
|
||||
table: WorkspaceDbTableName,
|
||||
row: &T,
|
||||
) -> StoreResult<Vec<u8>> {
|
||||
let doc_id = table.local_doc_id();
|
||||
let diff = self.db_table_mut(table).upsert_row(row)?;
|
||||
self.record_update(doc_id, diff.clone());
|
||||
Ok(diff)
|
||||
}
|
||||
|
||||
/// Partially patch fields on an existing non-deleted `db$` row and record any emitted update.
|
||||
pub fn patch_db_row_fields(
|
||||
&mut self,
|
||||
table: WorkspaceDbTableName,
|
||||
primary_key: &str,
|
||||
patches: &[(&str, Option<JsonValue>)],
|
||||
) -> StoreResult<Option<Vec<u8>>> {
|
||||
let doc_id = table.local_doc_id();
|
||||
let diff = self
|
||||
.db_table_mut(table)
|
||||
.patch_row_fields(primary_key, patches)?;
|
||||
if let Some(ref bytes) = diff {
|
||||
self.record_update(doc_id, bytes.clone());
|
||||
}
|
||||
Ok(diff)
|
||||
}
|
||||
|
||||
/// Soft-delete a row in a `db$` table and record any emitted update.
|
||||
pub fn soft_delete_db_row(
|
||||
&mut self,
|
||||
table: WorkspaceDbTableName,
|
||||
primary_key: &str,
|
||||
) -> StoreResult<Option<Vec<u8>>> {
|
||||
let doc_id = table.local_doc_id();
|
||||
let diff = self.db_table_mut(table).soft_delete(primary_key)?;
|
||||
if let Some(ref bytes) = diff {
|
||||
self.record_update(doc_id, bytes.clone());
|
||||
}
|
||||
Ok(diff)
|
||||
}
|
||||
|
||||
/// Upsert a row in a `userdata$` table and record the emitted update.
|
||||
pub fn upsert_userdata_row<T: Serialize>(
|
||||
&mut self,
|
||||
table: UserdataTableName,
|
||||
row: &T,
|
||||
) -> StoreResult<Vec<u8>> {
|
||||
let doc_id = table.local_doc_id(&self.user_id);
|
||||
let diff = self.userdata_table_mut(table).upsert_row(row)?;
|
||||
self.record_update(doc_id, diff.clone());
|
||||
Ok(diff)
|
||||
}
|
||||
|
||||
/// Partially patch fields on an existing non-deleted `userdata$` row and record any update.
|
||||
pub fn patch_userdata_row_fields(
|
||||
&mut self,
|
||||
table: UserdataTableName,
|
||||
primary_key: &str,
|
||||
patches: &[(&str, Option<JsonValue>)],
|
||||
) -> StoreResult<Option<Vec<u8>>> {
|
||||
let doc_id = table.local_doc_id(&self.user_id);
|
||||
let diff = self
|
||||
.userdata_table_mut(table)
|
||||
.patch_row_fields(primary_key, patches)?;
|
||||
if let Some(ref bytes) = diff {
|
||||
self.record_update(doc_id, bytes.clone());
|
||||
}
|
||||
Ok(diff)
|
||||
}
|
||||
|
||||
/// Soft-delete a row in a `userdata$` table and record any emitted update.
|
||||
pub fn soft_delete_userdata_row(
|
||||
&mut self,
|
||||
table: UserdataTableName,
|
||||
primary_key: &str,
|
||||
) -> StoreResult<Option<Vec<u8>>> {
|
||||
let doc_id = table.local_doc_id(&self.user_id);
|
||||
let diff = self.userdata_table_mut(table).soft_delete(primary_key)?;
|
||||
if let Some(ref bytes) = diff {
|
||||
self.record_update(doc_id, bytes.clone());
|
||||
}
|
||||
Ok(diff)
|
||||
}
|
||||
|
||||
/// Access a loaded `db$` table without creating or mutating it.
|
||||
pub fn db_table(&self, table: WorkspaceDbTableName) -> Option<&YjsTableDoc> {
|
||||
self.db_tables.get(&table)
|
||||
}
|
||||
|
||||
/// Access or lazily initialize a `db$` table for crate-internal writes.
|
||||
pub(crate) fn db_table_mut(&mut self, table: WorkspaceDbTableName) -> &mut YjsTableDoc {
|
||||
let client_id = self.client_id;
|
||||
self.db_tables.entry(table).or_insert_with(|| {
|
||||
YjsTableDoc::new(
|
||||
table.local_doc_id(),
|
||||
table.primary_key_field(),
|
||||
table.known_fields(),
|
||||
client_id,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Access a loaded `userdata$` table without creating or mutating it.
|
||||
pub fn userdata_table(&self, table: UserdataTableName) -> Option<&YjsTableDoc> {
|
||||
self.userdata_tables.get(&table)
|
||||
}
|
||||
|
||||
/// Access or lazily initialize a `userdata$` table for crate-internal writes.
|
||||
pub(crate) fn userdata_table_mut(&mut self, table: UserdataTableName) -> &mut YjsTableDoc {
|
||||
let client_id = self.client_id;
|
||||
let doc_id = table.local_doc_id(&self.user_id);
|
||||
self.userdata_tables.entry(table).or_insert_with(|| {
|
||||
YjsTableDoc::new(
|
||||
doc_id,
|
||||
table.primary_key_field(),
|
||||
table.known_fields(),
|
||||
client_id,
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn load_db_table_merges_remote_snapshot_without_losing_prior_local_writes() {
|
||||
let mut db = WorkspaceDb::new("ws-1", "u1", 1);
|
||||
|
||||
db.upsert_db_row(
|
||||
WorkspaceDbTableName::Folders,
|
||||
&FolderRow {
|
||||
id: "local-folder".into(),
|
||||
parent_id: None,
|
||||
data: "Local".into(),
|
||||
folder_type: "folder".into(),
|
||||
index: "a0".into(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(db.pending_updates().len(), 1);
|
||||
assert_eq!(db.pending_updates()[0].doc_id, "db$folders");
|
||||
|
||||
let mut remote = YjsTableDoc::new(
|
||||
WorkspaceDbTableName::Folders.local_doc_id(),
|
||||
WorkspaceDbTableName::Folders.primary_key_field(),
|
||||
WorkspaceDbTableName::Folders.known_fields(),
|
||||
2,
|
||||
);
|
||||
remote
|
||||
.upsert_row(&FolderRow {
|
||||
id: "remote-folder".into(),
|
||||
parent_id: None,
|
||||
data: "Remote".into(),
|
||||
folder_type: "folder".into(),
|
||||
index: "a1".into(),
|
||||
})
|
||||
.unwrap();
|
||||
let remote_bytes = remote.encode_update_v1().unwrap();
|
||||
|
||||
db.load_db_table(WorkspaceDbTableName::Folders, &remote_bytes)
|
||||
.unwrap();
|
||||
let rows = db
|
||||
.db_table(WorkspaceDbTableName::Folders)
|
||||
.unwrap()
|
||||
.list_rows::<FolderRow>()
|
||||
.unwrap();
|
||||
assert_eq!(rows.len(), 2);
|
||||
assert!(rows.iter().any(|r| r.id == "local-folder"));
|
||||
assert!(rows.iter().any(|r| r.id == "remote-folder"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn p4_patch_keeps_soft_deleted_row_deleted_and_does_not_create_missing_row() {
|
||||
let mut db = WorkspaceDb::new("ws", "u1", 1);
|
||||
db.upsert_db_row(
|
||||
WorkspaceDbTableName::Folders,
|
||||
&FolderRow {
|
||||
id: "f1".into(),
|
||||
parent_id: None,
|
||||
data: "Alpha".into(),
|
||||
folder_type: "folder".into(),
|
||||
index: "a0".into(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
db.soft_delete_db_row(WorkspaceDbTableName::Folders, "f1")
|
||||
.unwrap();
|
||||
let _ = db.drain_pending_updates();
|
||||
|
||||
assert!(
|
||||
db.patch_db_row_fields(
|
||||
WorkspaceDbTableName::Folders,
|
||||
"f1",
|
||||
&[("data", Some(json!("Renamed")))],
|
||||
)
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
db.patch_db_row_fields(
|
||||
WorkspaceDbTableName::Folders,
|
||||
"never-existed",
|
||||
&[("data", Some(json!("Ghost")))],
|
||||
)
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
assert!(db.pending_updates().is_empty());
|
||||
let table = db.db_table(WorkspaceDbTableName::Folders).unwrap();
|
||||
assert!(table.get_raw_row("never-existed").is_none());
|
||||
assert!(table.is_soft_deleted("f1").unwrap());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,772 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
use y_octo::{
|
||||
Any, DocOptions, DocSession, SessionConfig, SessionReadValue, SessionTxOrigin,
|
||||
SessionUndoConfig, SessionValue, TypePath, TypeTarget, YTypeKind,
|
||||
};
|
||||
|
||||
use crate::error::{StoreError, StoreResult};
|
||||
|
||||
const NANOID_URL_SAFE: &[u8; 64] =
|
||||
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";
|
||||
const DERIVED_PAGE_ID_LEN: usize = 10;
|
||||
|
||||
/// Deterministically derive a BlockSuite-compatible 10-character URL-safe NanoID
|
||||
/// (`[A-Za-z0-9_-]{10}`) from `(space_id, op_id)`.
|
||||
///
|
||||
/// Guarantees cross-restart `create_page` idempotency even if local sidecar caches are cleared
|
||||
/// by legacy clients or lost to a mid-transaction crash, without writing any extra keys into
|
||||
/// shared Yjs `meta.pages`.
|
||||
pub fn derive_page_id_for_op(space_id: &str, op_id: &str) -> String {
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(b"affine:create-page:v1:");
|
||||
hasher.update(space_id.as_bytes());
|
||||
hasher.update(b":");
|
||||
hasher.update(op_id.as_bytes());
|
||||
let digest = hasher.finalize();
|
||||
|
||||
let mut id = String::with_capacity(DERIVED_PAGE_ID_LEN);
|
||||
for &byte in &digest[..DERIVED_PAGE_ID_LEN] {
|
||||
id.push(NANOID_URL_SAFE[(byte & 0x3f) as usize] as char);
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// Metadata for one page entry in `rootDoc.meta.pages`.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct PageMetaEntry {
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
pub create_date_ms: i64,
|
||||
pub updated_date_ms: Option<i64>,
|
||||
pub tags: Vec<String>,
|
||||
pub trashed: bool,
|
||||
pub trash_date_ms: Option<i64>,
|
||||
}
|
||||
|
||||
/// Result of an idempotent `create_page` call.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct CreatePageOutcome {
|
||||
pub page_id: String,
|
||||
pub created_new: bool,
|
||||
/// Encoded v1 root-doc update emitted by this call, or `None` on idempotent retry.
|
||||
pub update: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// How a page's canonical ID is determined during [`WorkspaceRootDoc::create_page`].
|
||||
///
|
||||
/// Encoding the choice in a sum type prevents callers from passing both an `op_id` and an
|
||||
/// explicit `page_id` that would otherwise be silently ignored.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum PageIdSource<'a> {
|
||||
/// Deterministically derive a 10-character URL-safe NanoID from `(space_id, op_id)`
|
||||
/// via [`derive_page_id_for_op`].
|
||||
DerivedFromOp(&'a str),
|
||||
/// Use an explicit caller-chosen canonical page ID (for example, inline linked-doc creation
|
||||
/// where the reference block and target document must share a known ID).
|
||||
Explicit(&'a str),
|
||||
}
|
||||
|
||||
/// Result of applying a remote update to the root document.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct RemoteRootApply {
|
||||
/// Subdocument IDs newly present in `spaces` or announced via `subdocs_added`.
|
||||
pub newly_discovered_subdocs: Vec<String>,
|
||||
}
|
||||
|
||||
/// Authoritative coordinator for the AFFiNE workspace root YDoc (`meta.pages` + `spaces[pageId]`).
|
||||
pub struct WorkspaceRootDoc {
|
||||
space_id: String,
|
||||
root: DocSession<()>,
|
||||
baseline_sv: Vec<u8>,
|
||||
local_writeback: bool,
|
||||
revision: u64,
|
||||
}
|
||||
|
||||
impl WorkspaceRootDoc {
|
||||
/// Create a fresh uninitialized workspace root document.
|
||||
///
|
||||
/// Call [`Self::initialize_meta`] explicitly when bootstrapping a brand-new local workspace.
|
||||
pub fn new(space_id: impl Into<String>, client_id: u64) -> Self {
|
||||
let space_id = space_id.into();
|
||||
let options = DocOptions::from_identity(client_id, space_id.clone());
|
||||
let root = DocSession::with_config(
|
||||
options,
|
||||
SessionConfig {
|
||||
undo: SessionUndoConfig::Disabled,
|
||||
},
|
||||
);
|
||||
let baseline_sv = root.encode_state_vector_v1().unwrap_or_default();
|
||||
Self {
|
||||
space_id,
|
||||
root,
|
||||
baseline_sv,
|
||||
local_writeback: false,
|
||||
revision: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Load an existing root document from encoded v1 bytes with zero writeback.
|
||||
pub fn from_update_v1(
|
||||
space_id: impl Into<String>,
|
||||
client_id: u64,
|
||||
update: &[u8],
|
||||
) -> StoreResult<Self> {
|
||||
let mut doc = Self::new(space_id, client_id);
|
||||
if !update.is_empty() && update != [0, 0] {
|
||||
let commits = doc
|
||||
.root
|
||||
.apply_update_v1(update)
|
||||
.map_err(|err| StoreError::InvalidBinary(err.to_string()))?;
|
||||
doc.local_writeback = commits.iter().any(|c| {
|
||||
c.origin_kind == y_octo::SessionOriginKind::FormattingCleanup
|
||||
&& !c.update.is_empty()
|
||||
});
|
||||
doc.revision = doc.revision.wrapping_add(1);
|
||||
}
|
||||
doc.baseline_sv = doc
|
||||
.root
|
||||
.encode_state_vector_v1()
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))?;
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
pub fn space_id(&self) -> &str {
|
||||
&self.space_id
|
||||
}
|
||||
|
||||
/// Monotonically increasing revision bumped on every local commit and remote update,
|
||||
/// including delete-only updates that leave the Yjs state vector unchanged.
|
||||
pub fn revision(&self) -> u64 {
|
||||
self.revision
|
||||
}
|
||||
|
||||
/// Return `true` when `meta.pages` is initialized as a `Y.Array`.
|
||||
pub fn is_meta_initialized(&self) -> bool {
|
||||
let pages_target = TypeTarget::Path(TypePath::root("meta").key("pages"));
|
||||
self.root.read_array(&pages_target).is_ok()
|
||||
}
|
||||
|
||||
/// Explicitly initialize `meta.pages = []` for a brand-new local workspace.
|
||||
///
|
||||
/// Matches `0.27.5` `WorkspaceMeta.initialize()`. Returns `Ok(None)` with zero writeback
|
||||
/// when `meta.pages` is already an array.
|
||||
pub fn initialize_meta(&mut self) -> StoreResult<Option<Vec<u8>>> {
|
||||
if self.is_meta_initialized() {
|
||||
return Ok(None);
|
||||
}
|
||||
let meta_id = self
|
||||
.root
|
||||
.ensure_root("meta", YTypeKind::Map)
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))?;
|
||||
let _ = self
|
||||
.root
|
||||
.ensure_root("spaces", YTypeKind::Map)
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))?;
|
||||
let meta_target = TypeTarget::from(meta_id);
|
||||
|
||||
self.with_tx(|root| {
|
||||
root.map_set(
|
||||
&meta_target,
|
||||
"pages".to_string(),
|
||||
SessionValue::Array(Vec::new()),
|
||||
)
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))?;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Return `true` when local mutations have been written since load.
|
||||
pub fn has_local_writeback(&self) -> StoreResult<bool> {
|
||||
if self.local_writeback {
|
||||
return Ok(true);
|
||||
}
|
||||
let current_sv = self
|
||||
.root
|
||||
.encode_state_vector_v1()
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))?;
|
||||
Ok(current_sv != self.baseline_sv)
|
||||
}
|
||||
|
||||
/// Encode the full v1 update for persistence.
|
||||
pub fn encode_update_v1(&self) -> StoreResult<Vec<u8>> {
|
||||
self.root
|
||||
.encode_diff_v1(&[0])
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))
|
||||
}
|
||||
|
||||
/// Encode the current state vector.
|
||||
pub fn encode_state_vector_v1(&self) -> StoreResult<Vec<u8>> {
|
||||
self.root
|
||||
.encode_state_vector_v1()
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))
|
||||
}
|
||||
|
||||
/// Encode a v1 diff against `remote_sv`.
|
||||
pub fn encode_diff_v1(&self, remote_sv: &[u8]) -> StoreResult<Vec<u8>> {
|
||||
self.root
|
||||
.encode_diff_v1(remote_sv)
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))
|
||||
}
|
||||
|
||||
/// Atomically create a page in both `meta.pages` and `spaces[page_id]` in a single transaction.
|
||||
///
|
||||
/// Fails with [`StoreError::RootMetaNotInitialized`] if `meta.pages` is missing or not a
|
||||
/// `Y.Array` (never overwrites an unsynced remote `meta.pages`).
|
||||
///
|
||||
/// Writes only the frozen `0.27.5` `DocMeta` keys (`id`, `title`, `createDate`, `tags`) into
|
||||
/// shared Yjs. Idempotency is determined directly from `meta.pages` + `spaces` in the root
|
||||
/// YDoc using either [`PageIdSource::DerivedFromOp`] (`derive_page_id_for_op`) or
|
||||
/// [`PageIdSource::Explicit`] (caller-chosen canonical ID), with zero sidecar tables.
|
||||
pub fn create_page(
|
||||
&mut self,
|
||||
id_source: PageIdSource<'_>,
|
||||
title: &str,
|
||||
create_date_ms: i64,
|
||||
) -> StoreResult<CreatePageOutcome> {
|
||||
let effective_page_id = match id_source {
|
||||
PageIdSource::DerivedFromOp(op_id) => {
|
||||
if op_id.is_empty() {
|
||||
return Err(StoreError::InvalidProtocol(
|
||||
"create_page DerivedFromOp requires a non-empty op_id".into(),
|
||||
));
|
||||
}
|
||||
derive_page_id_for_op(&self.space_id, op_id)
|
||||
}
|
||||
PageIdSource::Explicit(page_id) => {
|
||||
if page_id.is_empty()
|
||||
|| page_id.starts_with("db$")
|
||||
|| page_id.starts_with("userdata$")
|
||||
{
|
||||
return Err(StoreError::InvalidProtocol(format!(
|
||||
"invalid explicit page_id: {page_id:?}"
|
||||
)));
|
||||
}
|
||||
page_id.to_string()
|
||||
}
|
||||
};
|
||||
|
||||
if effective_page_id == self.space_id {
|
||||
return Err(StoreError::InvalidProtocol(format!(
|
||||
"page_id must not collide with workspace root space_id {:?}",
|
||||
self.space_id
|
||||
)));
|
||||
}
|
||||
|
||||
if !self.is_meta_initialized() {
|
||||
return Err(StoreError::RootMetaNotInitialized);
|
||||
}
|
||||
|
||||
// Check both active/soft-deleted meta.pages and spaces[page_id] in the authoritative root
|
||||
// YDoc so retries neither duplicate entries nor return an incomplete/deleted page.
|
||||
let has_page = self.get_page(&effective_page_id)?.is_some();
|
||||
let has_space = self.subdoc_guids()?.contains_key(&effective_page_id);
|
||||
if has_page && has_space {
|
||||
return Ok(CreatePageOutcome {
|
||||
page_id: effective_page_id,
|
||||
created_new: false,
|
||||
update: None,
|
||||
});
|
||||
}
|
||||
|
||||
let spaces_id = self
|
||||
.root
|
||||
.ensure_root("spaces", YTypeKind::Map)
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))?;
|
||||
let spaces_target = TypeTarget::from(spaces_id);
|
||||
let pages_target = TypeTarget::Path(TypePath::root("meta").key("pages"));
|
||||
|
||||
let page_map = (!has_page).then(|| {
|
||||
SessionValue::Map(vec![
|
||||
(
|
||||
"id".to_string(),
|
||||
SessionValue::Any(Any::String(effective_page_id.clone())),
|
||||
),
|
||||
(
|
||||
"title".to_string(),
|
||||
SessionValue::Any(Any::String(title.to_string())),
|
||||
),
|
||||
(
|
||||
"createDate".to_string(),
|
||||
SessionValue::Any(Any::Float64((create_date_ms as f64).into())),
|
||||
),
|
||||
("tags".to_string(), SessionValue::Array(Vec::new())),
|
||||
])
|
||||
});
|
||||
|
||||
let update = self.with_tx(|root| {
|
||||
if let Some(map_val) = page_map {
|
||||
root.array_push(&pages_target, vec![map_val])
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))?;
|
||||
}
|
||||
if !has_space {
|
||||
root.map_set(
|
||||
&spaces_target,
|
||||
effective_page_id.clone(),
|
||||
SessionValue::Doc {
|
||||
guid: effective_page_id.clone(),
|
||||
gc: true,
|
||||
},
|
||||
)
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
Ok(CreatePageOutcome {
|
||||
page_id: effective_page_id,
|
||||
created_new: !has_page,
|
||||
update,
|
||||
})
|
||||
}
|
||||
|
||||
/// Update the title of `page_id` in `meta.pages`. Returns `Ok(None)` when unchanged.
|
||||
pub fn rename_page(&mut self, page_id: &str, new_title: &str) -> StoreResult<Option<Vec<u8>>> {
|
||||
let Some(target) = self.find_page_map_target(page_id)? else {
|
||||
return Err(StoreError::DocNotFound(page_id.to_string()));
|
||||
};
|
||||
|
||||
if matches!(
|
||||
self.root
|
||||
.get_map_value(&target, "title")
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))?,
|
||||
Some(SessionReadValue::Any(Any::String(ref current))) if current == new_title
|
||||
) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let commit = self
|
||||
.root
|
||||
.map_set(
|
||||
&target,
|
||||
"title".to_string(),
|
||||
SessionValue::Any(Any::String(new_title.to_string())),
|
||||
)
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))?;
|
||||
if commit.is_some() {
|
||||
self.local_writeback = true;
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
}
|
||||
|
||||
Ok(commit.map(|c| c.update))
|
||||
}
|
||||
|
||||
/// Soft-delete (move to trash) `page_id` in `meta.pages`.
|
||||
pub fn trash_page(
|
||||
&mut self,
|
||||
page_id: &str,
|
||||
trash_date_ms: i64,
|
||||
) -> StoreResult<Option<Vec<u8>>> {
|
||||
let Some(target) = self.find_page_map_target(page_id)? else {
|
||||
return Err(StoreError::DocNotFound(page_id.to_string()));
|
||||
};
|
||||
|
||||
if matches!(
|
||||
self.root
|
||||
.get_map_value(&target, "trash")
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))?,
|
||||
Some(SessionReadValue::Any(Any::True))
|
||||
) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
self.with_tx(|root| {
|
||||
root.map_set(&target, "trash".to_string(), SessionValue::Any(Any::True))
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))?;
|
||||
root.map_set(
|
||||
&target,
|
||||
"trashDate".to_string(),
|
||||
SessionValue::Any(Any::Float64((trash_date_ms as f64).into())),
|
||||
)
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))?;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Restore a soft-deleted page in `meta.pages`.
|
||||
pub fn restore_page(&mut self, page_id: &str) -> StoreResult<Option<Vec<u8>>> {
|
||||
let Some(target) = self.find_page_map_target(page_id)? else {
|
||||
return Err(StoreError::DocNotFound(page_id.to_string()));
|
||||
};
|
||||
|
||||
let is_trashed = matches!(
|
||||
self.root
|
||||
.get_map_value(&target, "trash")
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))?,
|
||||
Some(SessionReadValue::Any(Any::True))
|
||||
);
|
||||
if !is_trashed {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
self.with_tx(|root| {
|
||||
root.map_set(&target, "trash".to_string(), SessionValue::Any(Any::False))
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))?;
|
||||
root.map_remove(&target, "trashDate")
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))?;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Apply a remote update to the root document and report newly discovered subdoc GUIDs.
|
||||
pub fn apply_remote_update(&mut self, bytes: &[u8]) -> StoreResult<RemoteRootApply> {
|
||||
let before: BTreeSet<String> = self.subdoc_guids()?.into_values().collect();
|
||||
let commits = self
|
||||
.root
|
||||
.apply_update_v1(bytes)
|
||||
.map_err(|err| StoreError::InvalidBinary(err.to_string()))?;
|
||||
if !bytes.is_empty() && bytes != [0, 0] {
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
}
|
||||
|
||||
let mut discovered = BTreeSet::new();
|
||||
for commit in &commits {
|
||||
for guid in &commit.subdocs_added {
|
||||
if !before.contains(guid) {
|
||||
discovered.insert(guid.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
for guid in self.subdoc_guids()?.into_values() {
|
||||
if !before.contains(&guid) {
|
||||
discovered.insert(guid);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(RemoteRootApply {
|
||||
newly_discovered_subdocs: discovered.into_iter().collect(),
|
||||
})
|
||||
}
|
||||
|
||||
/// List all page metadata entries in `meta.pages` without mutating the document.
|
||||
pub fn list_pages(&self) -> StoreResult<Vec<PageMetaEntry>> {
|
||||
let pages_target = TypeTarget::Path(TypePath::root("meta").key("pages"));
|
||||
let Ok(items) = self.root.read_array(&pages_target) else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
|
||||
let mut result = Vec::new();
|
||||
for item in items {
|
||||
let SessionReadValue::Map(map_id) = item else {
|
||||
continue;
|
||||
};
|
||||
let entries = self
|
||||
.root
|
||||
.read_map(&TypeTarget::Identity(map_id))
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))?;
|
||||
let mut id = String::new();
|
||||
let mut title = String::new();
|
||||
let mut create_date_ms = 0i64;
|
||||
let mut updated_date_ms = None;
|
||||
let mut tags = Vec::new();
|
||||
let mut trashed = false;
|
||||
let mut trash_date_ms = None;
|
||||
|
||||
for (key, value) in entries {
|
||||
match key.as_str() {
|
||||
"id" => {
|
||||
if let SessionReadValue::Any(Any::String(s)) = value {
|
||||
id = s;
|
||||
}
|
||||
}
|
||||
"title" => {
|
||||
if let SessionReadValue::Any(Any::String(s)) = value {
|
||||
title = s;
|
||||
}
|
||||
}
|
||||
"createDate" => {
|
||||
if let Some(n) = any_to_i64(&value) {
|
||||
create_date_ms = n;
|
||||
}
|
||||
}
|
||||
"updatedDate" => {
|
||||
updated_date_ms = any_to_i64(&value);
|
||||
}
|
||||
"trash" => {
|
||||
trashed = matches!(value, SessionReadValue::Any(Any::True));
|
||||
}
|
||||
"trashDate" => {
|
||||
trash_date_ms = any_to_i64(&value);
|
||||
}
|
||||
"tags" => {
|
||||
if let SessionReadValue::Array(arr_id) = value {
|
||||
for tag in self
|
||||
.root
|
||||
.read_array(&TypeTarget::Identity(arr_id))
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))?
|
||||
{
|
||||
if let SessionReadValue::Any(Any::String(s)) = tag {
|
||||
tags.push(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
if !id.is_empty() {
|
||||
result.push(PageMetaEntry {
|
||||
id,
|
||||
title,
|
||||
create_date_ms,
|
||||
updated_date_ms,
|
||||
tags,
|
||||
trashed,
|
||||
trash_date_ms,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Read a single page metadata entry by `page_id`.
|
||||
pub fn get_page(&self, page_id: &str) -> StoreResult<Option<PageMetaEntry>> {
|
||||
Ok(self
|
||||
.list_pages()?
|
||||
.into_iter()
|
||||
.find(|entry| entry.id == page_id))
|
||||
}
|
||||
|
||||
/// Return `page_id -> subdoc_guid` from `spaces` without mutating the document.
|
||||
pub fn subdoc_guids(&self) -> StoreResult<BTreeMap<String, String>> {
|
||||
let spaces_target = TypeTarget::Path(TypePath::root("spaces"));
|
||||
let Ok(entries) = self.root.read_map(&spaces_target) else {
|
||||
return Ok(BTreeMap::new());
|
||||
};
|
||||
let mut out = BTreeMap::new();
|
||||
for (page_id, value) in entries {
|
||||
if let SessionReadValue::Doc { guid, .. } = value {
|
||||
out.insert(page_id, guid);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Execute `f` inside a `y-octo` transaction frame, guaranteeing `commit_tx()` always runs
|
||||
/// even when `f` returns an error so subsequent `apply_update_v1` calls are never locked out.
|
||||
///
|
||||
/// Callers must finish all read-only validation before entering `with_tx`.
|
||||
fn with_tx<F>(&mut self, f: F) -> StoreResult<Option<Vec<u8>>>
|
||||
where
|
||||
F: FnOnce(&mut DocSession<()>) -> StoreResult<()>,
|
||||
{
|
||||
self.root
|
||||
.begin_tx(SessionTxOrigin::Untracked)
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))?;
|
||||
let body_result = f(&mut self.root);
|
||||
let commit_result = self
|
||||
.root
|
||||
.commit_tx()
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()));
|
||||
if let Ok(Some(_)) = commit_result {
|
||||
self.local_writeback = true;
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
}
|
||||
body_result?;
|
||||
let commit = commit_result?;
|
||||
Ok(commit.map(|c| c.update))
|
||||
}
|
||||
|
||||
fn find_page_map_target(&self, page_id: &str) -> StoreResult<Option<TypeTarget>> {
|
||||
let pages_target = TypeTarget::Path(TypePath::root("meta").key("pages"));
|
||||
let Ok(items) = self.root.read_array(&pages_target) else {
|
||||
return Ok(None);
|
||||
};
|
||||
for item in items {
|
||||
if let SessionReadValue::Map(map_id) = item {
|
||||
let target = TypeTarget::Identity(map_id);
|
||||
if matches!(
|
||||
self.root
|
||||
.get_map_value(&target, "id")
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))?,
|
||||
Some(SessionReadValue::Any(Any::String(ref id))) if id == page_id
|
||||
) {
|
||||
return Ok(Some(target));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
fn any_to_i64(value: &SessionReadValue) -> Option<i64> {
|
||||
match value {
|
||||
SessionReadValue::Any(Any::Integer(n)) => Some(i64::from(*n)),
|
||||
SessionReadValue::Any(Any::BigInt64(n)) => Some(*n),
|
||||
SessionReadValue::Any(Any::Float64(f)) => Some(f.0 as i64),
|
||||
SessionReadValue::Any(Any::Float32(f)) => Some(f.0 as i64),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn create_page_rejects_uninitialized_meta_and_reserved_ids_without_writeback() {
|
||||
let mut root = WorkspaceRootDoc::new("ws-uninit", 1);
|
||||
assert!(!root.is_meta_initialized());
|
||||
let sv_before = root.encode_state_vector_v1().unwrap();
|
||||
let err = root
|
||||
.create_page(PageIdSource::DerivedFromOp("op-1"), "Should Fail", 1_000)
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, StoreError::RootMetaNotInitialized));
|
||||
assert!(matches!(
|
||||
root.create_page(PageIdSource::DerivedFromOp(""), "Empty Op", 1_000),
|
||||
Err(StoreError::InvalidProtocol(_))
|
||||
));
|
||||
assert!(matches!(
|
||||
root.create_page(PageIdSource::Explicit("db$folders"), "Bad Explicit", 1_000),
|
||||
Err(StoreError::InvalidProtocol(_))
|
||||
));
|
||||
assert!(matches!(
|
||||
root.create_page(
|
||||
PageIdSource::Explicit("ws-uninit"),
|
||||
"Root Space Collision",
|
||||
1_000
|
||||
),
|
||||
Err(StoreError::InvalidProtocol(_))
|
||||
));
|
||||
assert_eq!(root.encode_state_vector_v1().unwrap(), sv_before);
|
||||
assert!(!root.has_local_writeback().unwrap());
|
||||
|
||||
assert!(root.initialize_meta().unwrap().is_some());
|
||||
assert!(root.is_meta_initialized());
|
||||
assert!(root.initialize_meta().unwrap().is_none());
|
||||
let sv_init = root.encode_state_vector_v1().unwrap();
|
||||
assert!(matches!(
|
||||
root.create_page(
|
||||
PageIdSource::Explicit("ws-uninit"),
|
||||
"Root Space Collision",
|
||||
1_000
|
||||
),
|
||||
Err(StoreError::InvalidProtocol(_))
|
||||
));
|
||||
assert_eq!(root.encode_state_vector_v1().unwrap(), sv_init);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_rename_trash_restore_and_schema_purity_without_create_op_id() {
|
||||
let mut root = WorkspaceRootDoc::new("ws-1", 1);
|
||||
root.initialize_meta().unwrap();
|
||||
|
||||
let expected_id = derive_page_id_for_op("ws-1", "op-1");
|
||||
assert_eq!(expected_id.len(), 10);
|
||||
assert!(
|
||||
expected_id
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
|
||||
);
|
||||
|
||||
let first = root
|
||||
.create_page(PageIdSource::DerivedFromOp("op-1"), "Alpha", 1_000)
|
||||
.unwrap();
|
||||
assert!(first.created_new);
|
||||
assert_eq!(first.page_id, expected_id);
|
||||
assert!(first.update.is_some());
|
||||
assert_eq!(
|
||||
root.subdoc_guids()
|
||||
.unwrap()
|
||||
.get(&expected_id)
|
||||
.map(String::as_str),
|
||||
Some(expected_id.as_str())
|
||||
);
|
||||
|
||||
// Explicit caller-chosen ID (e.g. inline linked doc) preserves exact ID and is idempotent.
|
||||
let explicit = root
|
||||
.create_page(PageIdSource::Explicit("LinkedDoc01"), "Linked", 1_100)
|
||||
.unwrap();
|
||||
assert!(explicit.created_new);
|
||||
assert_eq!(explicit.page_id, "LinkedDoc01");
|
||||
let explicit_retry = root
|
||||
.create_page(PageIdSource::Explicit("LinkedDoc01"), "Linked", 1_200)
|
||||
.unwrap();
|
||||
assert!(!explicit_retry.created_new);
|
||||
assert_eq!(explicit_retry.page_id, "LinkedDoc01");
|
||||
assert!(explicit_retry.update.is_none());
|
||||
|
||||
// Verify shared Yjs meta.pages entry contains ONLY 0.27.5 keys (never createOpId).
|
||||
let page_target = root.find_page_map_target(&expected_id).unwrap().unwrap();
|
||||
let raw_entries = root.root.read_map(&page_target).unwrap();
|
||||
let keys: BTreeSet<String> = raw_entries.into_iter().map(|(k, _)| k).collect();
|
||||
assert!(!keys.contains("createOpId"));
|
||||
assert_eq!(
|
||||
keys,
|
||||
BTreeSet::from([
|
||||
"id".to_string(),
|
||||
"title".to_string(),
|
||||
"createDate".to_string(),
|
||||
"tags".to_string(),
|
||||
])
|
||||
);
|
||||
|
||||
// Reload from root Yjs bytes alone: deterministic derivation hits with zero writeback!
|
||||
let encoded = root.encode_update_v1().unwrap();
|
||||
let mut reloaded = WorkspaceRootDoc::from_update_v1("ws-1", 2, &encoded).unwrap();
|
||||
assert!(!reloaded.has_local_writeback().unwrap());
|
||||
let sv_before_retry = reloaded.encode_state_vector_v1().unwrap();
|
||||
|
||||
let retry = reloaded
|
||||
.create_page(PageIdSource::DerivedFromOp("op-1"), "Alpha", 2_000)
|
||||
.unwrap();
|
||||
assert!(!retry.created_new);
|
||||
assert_eq!(retry.page_id, expected_id);
|
||||
assert!(retry.update.is_none());
|
||||
assert_eq!(reloaded.encode_state_vector_v1().unwrap(), sv_before_retry);
|
||||
assert!(!reloaded.has_local_writeback().unwrap());
|
||||
assert_eq!(reloaded.list_pages().unwrap().len(), 2);
|
||||
|
||||
// Unchanged rename produces zero writeback; changed rename updates title.
|
||||
assert!(root.rename_page(&expected_id, "Alpha").unwrap().is_none());
|
||||
assert!(root.rename_page(&expected_id, "Beta").unwrap().is_some());
|
||||
assert_eq!(root.get_page(&expected_id).unwrap().unwrap().title, "Beta");
|
||||
|
||||
// Trash and restore.
|
||||
assert!(root.trash_page(&expected_id, 2_000).unwrap().is_some());
|
||||
let trashed = root.get_page(&expected_id).unwrap().unwrap();
|
||||
assert!(trashed.trashed);
|
||||
assert_eq!(trashed.trash_date_ms, Some(2_000));
|
||||
|
||||
assert!(root.restore_page(&expected_id).unwrap().is_some());
|
||||
let restored = root.get_page(&expected_id).unwrap().unwrap();
|
||||
assert!(!restored.trashed);
|
||||
assert_eq!(restored.trash_date_ms, None);
|
||||
|
||||
// Remote subdoc discovery.
|
||||
let encoded_after = root.encode_update_v1().unwrap();
|
||||
let mut peer = WorkspaceRootDoc::from_update_v1("ws-1", 3, &encoded_after).unwrap();
|
||||
let new_page = root
|
||||
.create_page(PageIdSource::DerivedFromOp("op-2"), "Gamma", 3_000)
|
||||
.unwrap();
|
||||
let applied = peer
|
||||
.apply_remote_update(new_page.update.as_deref().unwrap())
|
||||
.unwrap();
|
||||
assert_eq!(applied.newly_discovered_subdocs, vec![new_page.page_id]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_transaction_closes_tx_frame_so_remote_updates_still_apply() {
|
||||
let mut root = WorkspaceRootDoc::new("ws-tx", 1);
|
||||
root.initialize_meta().unwrap();
|
||||
|
||||
let err = root
|
||||
.with_tx(|_| Err(StoreError::InvalidProtocol("injected fault".into())))
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, StoreError::InvalidProtocol(_)));
|
||||
|
||||
let mut peer =
|
||||
WorkspaceRootDoc::from_update_v1("ws-tx", 2, &root.encode_update_v1().unwrap())
|
||||
.unwrap();
|
||||
let created = peer
|
||||
.create_page(PageIdSource::DerivedFromOp("op-peer"), "Peer", 500)
|
||||
.unwrap();
|
||||
let applied = root
|
||||
.apply_remote_update(created.update.as_deref().unwrap())
|
||||
.unwrap();
|
||||
assert_eq!(applied.newly_discovered_subdocs, vec![created.page_id]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,921 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value as JsonValue;
|
||||
use y_octo::{AHashMap, Any, Doc, DocOptions, HashMapExt, StateVector, Value};
|
||||
|
||||
use crate::error::{StoreError, StoreResult};
|
||||
|
||||
/// Soft-delete marker written by `YjsTableAdapter` (`packages/common/infra/src/orm/core/adapters/yjs/table.ts`).
|
||||
pub const DELETED_FLAG_KEY: &str = "$$DELETED";
|
||||
|
||||
/// JavaScript safe integer bounds (`Number.MAX_SAFE_INTEGER` / `Number.MIN_SAFE_INTEGER`).
|
||||
const JS_MAX_SAFE_INTEGER: i64 = (1i64 << 53) - 1;
|
||||
const JS_MIN_SAFE_INTEGER: i64 = -JS_MAX_SAFE_INTEGER;
|
||||
|
||||
/// All 5 workspace `db$` table names.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
|
||||
pub enum WorkspaceDbTableName {
|
||||
Folders,
|
||||
DocProperties,
|
||||
DocCustomPropertyInfo,
|
||||
PinnedCollections,
|
||||
ExplorerIcon,
|
||||
}
|
||||
|
||||
pub const WORKSPACE_DB_TABLE_NAMES: &[WorkspaceDbTableName] = &[
|
||||
WorkspaceDbTableName::Folders,
|
||||
WorkspaceDbTableName::DocProperties,
|
||||
WorkspaceDbTableName::DocCustomPropertyInfo,
|
||||
WorkspaceDbTableName::PinnedCollections,
|
||||
WorkspaceDbTableName::ExplorerIcon,
|
||||
];
|
||||
|
||||
impl WorkspaceDbTableName {
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Folders => "folders",
|
||||
Self::DocProperties => "docProperties",
|
||||
Self::DocCustomPropertyInfo => "docCustomPropertyInfo",
|
||||
Self::PinnedCollections => "pinnedCollections",
|
||||
Self::ExplorerIcon => "explorerIcon",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn local_doc_id(self) -> String {
|
||||
format!("db${}", self.as_str())
|
||||
}
|
||||
|
||||
pub const fn primary_key_field(self) -> &'static str {
|
||||
match self {
|
||||
Self::PinnedCollections => "collectionId",
|
||||
Self::Folders
|
||||
| Self::DocProperties
|
||||
| Self::DocCustomPropertyInfo
|
||||
| Self::ExplorerIcon => "id",
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn known_fields(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
Self::Folders => &["id", "parentId", "data", "type", "index"],
|
||||
Self::DocProperties => &[
|
||||
"id",
|
||||
"primaryMode",
|
||||
"edgelessColorTheme",
|
||||
"journal",
|
||||
"pageWidth",
|
||||
"isTemplate",
|
||||
"integrationType",
|
||||
"createdBy",
|
||||
"updatedBy",
|
||||
],
|
||||
Self::DocCustomPropertyInfo => &[
|
||||
"id",
|
||||
"name",
|
||||
"type",
|
||||
"show",
|
||||
"index",
|
||||
"icon",
|
||||
"additionalData",
|
||||
"isDeleted",
|
||||
],
|
||||
Self::PinnedCollections => &["collectionId", "index"],
|
||||
Self::ExplorerIcon => &["id", "icon"],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// All 3 `userdata$` table names.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
|
||||
pub enum UserdataTableName {
|
||||
Favorite,
|
||||
Settings,
|
||||
DocIntegrationRef,
|
||||
}
|
||||
|
||||
pub const USERDATA_TABLE_NAMES: &[UserdataTableName] = &[
|
||||
UserdataTableName::Favorite,
|
||||
UserdataTableName::Settings,
|
||||
UserdataTableName::DocIntegrationRef,
|
||||
];
|
||||
|
||||
impl UserdataTableName {
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Favorite => "favorite",
|
||||
Self::Settings => "settings",
|
||||
Self::DocIntegrationRef => "docIntegrationRef",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn local_doc_id(self, user_id: &str) -> String {
|
||||
format!("userdata${user_id}${}", self.as_str())
|
||||
}
|
||||
|
||||
pub const fn primary_key_field(self) -> &'static str {
|
||||
match self {
|
||||
Self::Favorite | Self::Settings => "key",
|
||||
Self::DocIntegrationRef => "id",
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn known_fields(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
Self::Favorite => &["key", "index"],
|
||||
Self::Settings => &["key", "value"],
|
||||
Self::DocIntegrationRef => &["id", "type", "integrationId", "refMeta"],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FolderRow {
|
||||
pub id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub parent_id: Option<String>,
|
||||
pub data: String,
|
||||
#[serde(rename = "type")]
|
||||
pub folder_type: String,
|
||||
pub index: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DocPropertiesRow {
|
||||
pub id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub primary_mode: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub edgeless_color_theme: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub journal: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub page_width: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub is_template: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub integration_type: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub created_by: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub updated_by: Option<String>,
|
||||
#[serde(flatten)]
|
||||
pub custom_fields: BTreeMap<String, JsonValue>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DocCustomPropertyInfoRow {
|
||||
pub id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
#[serde(rename = "type")]
|
||||
pub property_type: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub show: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub index: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub icon: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub additional_data: Option<JsonValue>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub is_deleted: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PinnedCollectionRow {
|
||||
pub collection_id: String,
|
||||
pub index: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExplorerIconRow {
|
||||
pub id: String,
|
||||
pub icon: JsonValue,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FavoriteRow {
|
||||
pub key: String,
|
||||
pub index: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SettingsRow {
|
||||
pub key: String,
|
||||
pub value: JsonValue,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DocIntegrationRefRow {
|
||||
pub id: String,
|
||||
#[serde(rename = "type")]
|
||||
pub integration_type: String,
|
||||
pub integration_id: String,
|
||||
pub ref_meta: JsonValue,
|
||||
}
|
||||
|
||||
/// Primary-key `Y.Map` table backed by a single `y-octo::Doc`, matching `YjsTableAdapter`.
|
||||
pub struct YjsTableDoc {
|
||||
doc_id: String,
|
||||
key_field: &'static str,
|
||||
known_fields: &'static [&'static str],
|
||||
doc: Doc,
|
||||
baseline_sv: StateVector,
|
||||
local_writeback: bool,
|
||||
revision: u64,
|
||||
}
|
||||
|
||||
impl YjsTableDoc {
|
||||
pub fn new(
|
||||
doc_id: impl Into<String>,
|
||||
key_field: &'static str,
|
||||
known_fields: &'static [&'static str],
|
||||
client_id: u64,
|
||||
) -> Self {
|
||||
let doc_id = doc_id.into();
|
||||
let doc = DocOptions::from_identity(client_id, doc_id.clone()).build();
|
||||
let baseline_sv = doc.get_state_vector();
|
||||
Self {
|
||||
doc_id,
|
||||
key_field,
|
||||
known_fields,
|
||||
doc,
|
||||
baseline_sv,
|
||||
local_writeback: false,
|
||||
revision: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Load a table document from encoded v1 bytes with zero writeback.
|
||||
pub fn from_update_v1(
|
||||
doc_id: impl Into<String>,
|
||||
key_field: &'static str,
|
||||
known_fields: &'static [&'static str],
|
||||
client_id: u64,
|
||||
update: &[u8],
|
||||
) -> StoreResult<Self> {
|
||||
let mut table = Self::new(doc_id, key_field, known_fields, client_id);
|
||||
if !update.is_empty() && update != [0, 0] {
|
||||
table
|
||||
.doc
|
||||
.apply_update_from_binary_v1(update)
|
||||
.map_err(|err| StoreError::InvalidBinary(err.to_string()))?;
|
||||
table.revision = table.revision.wrapping_add(1);
|
||||
}
|
||||
table.baseline_sv = table.doc.get_state_vector();
|
||||
table.local_writeback = false;
|
||||
Ok(table)
|
||||
}
|
||||
|
||||
/// CRDT-merge an encoded v1 update into this table document without losing local writes.
|
||||
pub fn apply_update_v1(&mut self, update: &[u8]) -> StoreResult<()> {
|
||||
if !update.is_empty() && update != [0, 0] {
|
||||
self.doc
|
||||
.apply_update_from_binary_v1(update)
|
||||
.map_err(|err| StoreError::InvalidBinary(err.to_string()))?;
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn doc_id(&self) -> &str {
|
||||
&self.doc_id
|
||||
}
|
||||
|
||||
/// Monotonically increasing revision bumped on every local write and remote update,
|
||||
/// including delete-only updates that leave the Yjs state vector unchanged.
|
||||
pub fn revision(&self) -> u64 {
|
||||
self.revision
|
||||
}
|
||||
|
||||
/// Return `true` when local writes have occurred since load.
|
||||
pub fn has_local_writeback(&self) -> StoreResult<bool> {
|
||||
Ok(self.local_writeback || self.doc.get_state_vector() != self.baseline_sv)
|
||||
}
|
||||
|
||||
pub fn encode_update_v1(&self) -> StoreResult<Vec<u8>> {
|
||||
self.doc
|
||||
.encode_update_v1()
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))
|
||||
}
|
||||
|
||||
/// Upsert a typed row by primary key, removing `$$DELETED` if previously soft-deleted.
|
||||
pub fn upsert_row<T: Serialize>(&mut self, row: &T) -> StoreResult<Vec<u8>> {
|
||||
let before_sv = self.doc.get_state_vector();
|
||||
let JsonValue::Object(obj) = serde_json::to_value(row)? else {
|
||||
return Err(StoreError::InvalidProtocol(
|
||||
"table row must serialize as a JSON object".into(),
|
||||
));
|
||||
};
|
||||
let Some(key) = obj.get(self.key_field).and_then(JsonValue::as_str) else {
|
||||
return Err(StoreError::InvalidProtocol(format!(
|
||||
"missing string primary key field `{}`",
|
||||
self.key_field
|
||||
)));
|
||||
};
|
||||
|
||||
let mut map = self
|
||||
.doc
|
||||
.get_or_create_map(key)
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))?;
|
||||
for (field, val) in &obj {
|
||||
map.insert(field.clone(), Value::Any(json_to_any(val)))
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))?;
|
||||
}
|
||||
map.remove(DELETED_FLAG_KEY);
|
||||
self.local_writeback = true;
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
|
||||
self.doc
|
||||
.encode_state_as_update_v1(&before_sv)
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))
|
||||
}
|
||||
|
||||
/// Partially update specific fields on an existing non-deleted row, matching `0.27.5`
|
||||
/// `YjsTableAdapter.update` (`table.ts:81-96, 184-191`).
|
||||
///
|
||||
/// Returns `Ok(None)` with zero writeback when `primary_key` does not exist or is
|
||||
/// soft-deleted (never resurrects a deleted row or creates a ghost row).
|
||||
pub fn patch_row_fields(
|
||||
&mut self,
|
||||
primary_key: &str,
|
||||
patches: &[(&str, Option<JsonValue>)],
|
||||
) -> StoreResult<Option<Vec<u8>>> {
|
||||
let Ok(mut map) = self.doc.get_map(primary_key) else {
|
||||
return Ok(None);
|
||||
};
|
||||
if is_map_deleted(&map) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let before_sv = self.doc.get_state_vector();
|
||||
let mut mutated = false;
|
||||
for (field, value) in patches {
|
||||
if *field == self.key_field || *field == DELETED_FLAG_KEY {
|
||||
continue;
|
||||
}
|
||||
match value {
|
||||
Some(val) => {
|
||||
map.insert((*field).to_string(), Value::Any(json_to_any(val)))
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))?;
|
||||
mutated = true;
|
||||
}
|
||||
None => {
|
||||
if map.get(field).is_some() {
|
||||
map.remove(field);
|
||||
mutated = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !mutated {
|
||||
return Ok(None);
|
||||
}
|
||||
self.local_writeback = true;
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
|
||||
let diff = self
|
||||
.doc
|
||||
.encode_state_as_update_v1(&before_sv)
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))?;
|
||||
Ok(Some(diff))
|
||||
}
|
||||
|
||||
/// Soft-delete a row matching `YjsTableAdapter.deleteTy` (`table.ts:288-295`): remove only
|
||||
/// known non-key schema fields and set `$$DELETED = true`, preserving unknown extension keys.
|
||||
pub fn soft_delete(&mut self, primary_key: &str) -> StoreResult<Option<Vec<u8>>> {
|
||||
let Ok(mut map) = self.doc.get_map(primary_key) else {
|
||||
return Ok(None);
|
||||
};
|
||||
if is_map_deleted(&map) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let before_sv = self.doc.get_state_vector();
|
||||
for field in self.known_fields {
|
||||
if *field != self.key_field {
|
||||
map.remove(field);
|
||||
}
|
||||
}
|
||||
map.insert(DELETED_FLAG_KEY.to_string(), Value::Any(Any::True))
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))?;
|
||||
self.local_writeback = true;
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
|
||||
let diff = self
|
||||
.doc
|
||||
.encode_state_as_update_v1(&before_sv)
|
||||
.map_err(|err| StoreError::YOcto(err.to_string()))?;
|
||||
Ok(Some(diff))
|
||||
}
|
||||
|
||||
/// Read a single non-deleted row by primary key via direct root map lookup.
|
||||
pub fn get_row<T: for<'de> Deserialize<'de>>(
|
||||
&self,
|
||||
primary_key: &str,
|
||||
) -> StoreResult<Option<T>> {
|
||||
let Ok(map) = self.doc.get_map(primary_key) else {
|
||||
return Ok(None);
|
||||
};
|
||||
if is_map_deleted(&map) {
|
||||
return Ok(None);
|
||||
}
|
||||
let json = map_to_json_object(&map);
|
||||
Ok(Some(serde_json::from_value(json)?))
|
||||
}
|
||||
|
||||
/// Read raw JSON fields of a non-deleted row (including unknown extension keys).
|
||||
pub fn get_raw_row(&self, primary_key: &str) -> Option<JsonValue> {
|
||||
let map = self.doc.get_map(primary_key).ok()?;
|
||||
if is_map_deleted(&map) {
|
||||
return None;
|
||||
}
|
||||
Some(map_to_json_object(&map))
|
||||
}
|
||||
|
||||
/// List all valid non-deleted rows in deterministic key order, skipping corrupt rows instead
|
||||
/// of failing the entire table query.
|
||||
pub fn list_rows<T: for<'de> Deserialize<'de>>(&self) -> StoreResult<Vec<T>> {
|
||||
let mut keys = self.doc.keys();
|
||||
keys.sort();
|
||||
let mut rows = Vec::new();
|
||||
for key in keys {
|
||||
if let Ok(Some(row)) = self.get_row::<T>(&key) {
|
||||
rows.push(row);
|
||||
}
|
||||
}
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
/// Return `true` if `primary_key` exists in the underlying YDoc with `$$DELETED = true`.
|
||||
pub fn is_soft_deleted(&self, primary_key: &str) -> StoreResult<bool> {
|
||||
let Ok(map) = self.doc.get_map(primary_key) else {
|
||||
return Ok(false);
|
||||
};
|
||||
Ok(matches!(
|
||||
map.get(DELETED_FLAG_KEY),
|
||||
Some(Value::Any(Any::True))
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn is_map_deleted(map: &y_octo::Map) -> bool {
|
||||
if map.is_empty() {
|
||||
return true;
|
||||
}
|
||||
matches!(map.get(DELETED_FLAG_KEY), Some(Value::Any(Any::True)))
|
||||
}
|
||||
|
||||
fn map_to_json_object(map: &y_octo::Map) -> JsonValue {
|
||||
let mut obj = serde_json::Map::new();
|
||||
for (k, v) in map.iter() {
|
||||
if k == DELETED_FLAG_KEY {
|
||||
continue;
|
||||
}
|
||||
if let Value::Any(any) = v {
|
||||
obj.insert(k.to_string(), any_to_json(&any));
|
||||
}
|
||||
}
|
||||
JsonValue::Object(obj)
|
||||
}
|
||||
|
||||
fn any_to_json(any: &Any) -> JsonValue {
|
||||
match any {
|
||||
Any::Null | Any::Undefined => JsonValue::Null,
|
||||
Any::False => JsonValue::Bool(false),
|
||||
Any::True => JsonValue::Bool(true),
|
||||
Any::Integer(n) => JsonValue::Number((*n).into()),
|
||||
Any::BigInt64(n) => JsonValue::Number((*n).into()),
|
||||
Any::Float32(f) => serde_json::Number::from_f64(f64::from(f.0))
|
||||
.map(JsonValue::Number)
|
||||
.unwrap_or(JsonValue::Null),
|
||||
Any::Float64(f) => {
|
||||
let v = f.0;
|
||||
if v.is_finite()
|
||||
&& v.fract() == 0.0
|
||||
&& v >= (JS_MIN_SAFE_INTEGER as f64)
|
||||
&& v <= (JS_MAX_SAFE_INTEGER as f64)
|
||||
{
|
||||
JsonValue::Number((v as i64).into())
|
||||
} else {
|
||||
serde_json::Number::from_f64(v)
|
||||
.map(JsonValue::Number)
|
||||
.unwrap_or(JsonValue::Null)
|
||||
}
|
||||
}
|
||||
Any::String(s) => JsonValue::String(s.clone()),
|
||||
Any::Array(arr) => JsonValue::Array(arr.iter().map(any_to_json).collect()),
|
||||
Any::Object(map) => {
|
||||
let mut obj = serde_json::Map::new();
|
||||
for (k, v) in map.iter() {
|
||||
obj.insert(k.clone(), any_to_json(v));
|
||||
}
|
||||
JsonValue::Object(obj)
|
||||
}
|
||||
Any::Binary(bytes) => JsonValue::Array(bytes.iter().map(|b| (*b).into()).collect()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert JSON values to `y-octo::Any` without ever producing lib0 `BigInt64` (tag `0x7a`),
|
||||
/// matching JS `YjsTableAdapter` where integers above `i32` serialize as IEEE 754 `Float64`.
|
||||
fn json_to_any(value: &JsonValue) -> Any {
|
||||
match value {
|
||||
JsonValue::Null => Any::Null,
|
||||
JsonValue::Bool(true) => Any::True,
|
||||
JsonValue::Bool(false) => Any::False,
|
||||
JsonValue::Number(n) => {
|
||||
if let Some(i) = n.as_i64() {
|
||||
if let Ok(i32_val) = i32::try_from(i) {
|
||||
Any::Integer(i32_val)
|
||||
} else {
|
||||
Any::Float64((i as f64).into())
|
||||
}
|
||||
} else if let Some(u) = n.as_u64() {
|
||||
if let Ok(i32_val) = i32::try_from(u) {
|
||||
Any::Integer(i32_val)
|
||||
} else {
|
||||
Any::Float64((u as f64).into())
|
||||
}
|
||||
} else if let Some(f) = n.as_f64() {
|
||||
Any::Float64(f.into())
|
||||
} else {
|
||||
Any::Null
|
||||
}
|
||||
}
|
||||
JsonValue::String(s) => Any::String(s.clone()),
|
||||
JsonValue::Array(arr) => Any::Array(arr.iter().map(json_to_any).collect()),
|
||||
JsonValue::Object(obj) => {
|
||||
let mut map = AHashMap::with_capacity(obj.len());
|
||||
for (k, v) in obj {
|
||||
map.insert(k.clone(), json_to_any(v));
|
||||
}
|
||||
Any::Object(Box::new(map))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn all_eight_tables_support_typed_upsert_soft_delete_reinsert_and_zero_writeback() {
|
||||
let mut folders = YjsTableDoc::new(
|
||||
WorkspaceDbTableName::Folders.local_doc_id(),
|
||||
WorkspaceDbTableName::Folders.primary_key_field(),
|
||||
WorkspaceDbTableName::Folders.known_fields(),
|
||||
1,
|
||||
);
|
||||
folders
|
||||
.upsert_row(&FolderRow {
|
||||
id: "f1".into(),
|
||||
parent_id: None,
|
||||
data: "Root".into(),
|
||||
folder_type: "folder".into(),
|
||||
index: "a0".into(),
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(folders.list_rows::<FolderRow>().unwrap().len(), 1);
|
||||
folders.soft_delete("f1").unwrap();
|
||||
assert!(folders.is_soft_deleted("f1").unwrap());
|
||||
assert!(folders.get_row::<FolderRow>("f1").unwrap().is_none());
|
||||
folders
|
||||
.upsert_row(&FolderRow {
|
||||
id: "f1".into(),
|
||||
parent_id: Some("root".into()),
|
||||
data: "Restored".into(),
|
||||
folder_type: "folder".into(),
|
||||
index: "a1".into(),
|
||||
})
|
||||
.unwrap();
|
||||
assert!(!folders.is_soft_deleted("f1").unwrap());
|
||||
assert_eq!(
|
||||
folders.get_row::<FolderRow>("f1").unwrap().unwrap().data,
|
||||
"Restored"
|
||||
);
|
||||
|
||||
let mut props = YjsTableDoc::new(
|
||||
WorkspaceDbTableName::DocProperties.local_doc_id(),
|
||||
WorkspaceDbTableName::DocProperties.primary_key_field(),
|
||||
WorkspaceDbTableName::DocProperties.known_fields(),
|
||||
1,
|
||||
);
|
||||
let mut custom = BTreeMap::new();
|
||||
custom.insert("custom:priority".to_string(), json!("high"));
|
||||
props
|
||||
.upsert_row(&DocPropertiesRow {
|
||||
id: "doc-1".into(),
|
||||
primary_mode: Some("edgeless".into()),
|
||||
edgeless_color_theme: None,
|
||||
journal: None,
|
||||
page_width: Some("fullWidth".into()),
|
||||
is_template: Some(false),
|
||||
integration_type: None,
|
||||
created_by: Some("u1".into()),
|
||||
updated_by: None,
|
||||
custom_fields: custom,
|
||||
})
|
||||
.unwrap();
|
||||
let loaded_props = YjsTableDoc::from_update_v1(
|
||||
WorkspaceDbTableName::DocProperties.local_doc_id(),
|
||||
WorkspaceDbTableName::DocProperties.primary_key_field(),
|
||||
WorkspaceDbTableName::DocProperties.known_fields(),
|
||||
2,
|
||||
&props.encode_update_v1().unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!loaded_props.has_local_writeback().unwrap());
|
||||
let row = loaded_props
|
||||
.get_row::<DocPropertiesRow>("doc-1")
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(row.primary_mode.as_deref(), Some("edgeless"));
|
||||
assert_eq!(
|
||||
row.custom_fields.get("custom:priority"),
|
||||
Some(&json!("high"))
|
||||
);
|
||||
|
||||
let mut custom_info = YjsTableDoc::new(
|
||||
WorkspaceDbTableName::DocCustomPropertyInfo.local_doc_id(),
|
||||
WorkspaceDbTableName::DocCustomPropertyInfo.primary_key_field(),
|
||||
WorkspaceDbTableName::DocCustomPropertyInfo.known_fields(),
|
||||
1,
|
||||
);
|
||||
custom_info
|
||||
.upsert_row(&DocCustomPropertyInfoRow {
|
||||
id: "cp1".into(),
|
||||
name: Some("Status".into()),
|
||||
property_type: "text".into(),
|
||||
show: Some("always-show".into()),
|
||||
index: Some("a0".into()),
|
||||
icon: None,
|
||||
additional_data: Some(json!({"choices": ["todo", "done"]})),
|
||||
is_deleted: Some(false),
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
custom_info
|
||||
.get_row::<DocCustomPropertyInfoRow>("cp1")
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.name
|
||||
.as_deref(),
|
||||
Some("Status")
|
||||
);
|
||||
|
||||
let mut pinned = YjsTableDoc::new(
|
||||
WorkspaceDbTableName::PinnedCollections.local_doc_id(),
|
||||
WorkspaceDbTableName::PinnedCollections.primary_key_field(),
|
||||
WorkspaceDbTableName::PinnedCollections.known_fields(),
|
||||
1,
|
||||
);
|
||||
pinned
|
||||
.upsert_row(&PinnedCollectionRow {
|
||||
collection_id: "col-1".into(),
|
||||
index: "a0".into(),
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(pinned.list_rows::<PinnedCollectionRow>().unwrap().len(), 1);
|
||||
|
||||
let mut icons = YjsTableDoc::new(
|
||||
WorkspaceDbTableName::ExplorerIcon.local_doc_id(),
|
||||
WorkspaceDbTableName::ExplorerIcon.primary_key_field(),
|
||||
WorkspaceDbTableName::ExplorerIcon.known_fields(),
|
||||
1,
|
||||
);
|
||||
icons
|
||||
.upsert_row(&ExplorerIconRow {
|
||||
id: "doc:doc-1".into(),
|
||||
icon: json!({"type": "emoji", "unicode": "1f4dd"}),
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(icons.list_rows::<ExplorerIconRow>().unwrap().len(), 1);
|
||||
|
||||
let mut fav = YjsTableDoc::new(
|
||||
UserdataTableName::Favorite.local_doc_id("u1"),
|
||||
UserdataTableName::Favorite.primary_key_field(),
|
||||
UserdataTableName::Favorite.known_fields(),
|
||||
1,
|
||||
);
|
||||
fav.upsert_row(&FavoriteRow {
|
||||
key: "doc:doc-1".into(),
|
||||
index: "a0".into(),
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(fav.list_rows::<FavoriteRow>().unwrap().len(), 1);
|
||||
|
||||
let mut settings = YjsTableDoc::new(
|
||||
UserdataTableName::Settings.local_doc_id("u1"),
|
||||
UserdataTableName::Settings.primary_key_field(),
|
||||
UserdataTableName::Settings.known_fields(),
|
||||
1,
|
||||
);
|
||||
settings
|
||||
.upsert_row(&SettingsRow {
|
||||
key: "theme".into(),
|
||||
value: json!("dark"),
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
settings
|
||||
.get_row::<SettingsRow>("theme")
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.value,
|
||||
json!("dark")
|
||||
);
|
||||
|
||||
let mut refs = YjsTableDoc::new(
|
||||
UserdataTableName::DocIntegrationRef.local_doc_id("u1"),
|
||||
UserdataTableName::DocIntegrationRef.primary_key_field(),
|
||||
UserdataTableName::DocIntegrationRef.known_fields(),
|
||||
1,
|
||||
);
|
||||
refs.upsert_row(&DocIntegrationRefRow {
|
||||
id: "doc-1".into(),
|
||||
integration_type: "readwise".into(),
|
||||
integration_id: "rw-1".into(),
|
||||
ref_meta: json!({"bookId": 42}),
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(refs.list_rows::<DocIntegrationRefRow>().unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soft_delete_preserves_unknown_extension_keys_across_reinsert() {
|
||||
let raw_doc = DocOptions::from_identity(1, "db$folders".into()).build();
|
||||
let mut raw_map = raw_doc.get_or_create_map("f-ext").unwrap();
|
||||
raw_map
|
||||
.insert("id".to_string(), Value::Any(Any::String("f-ext".into())))
|
||||
.unwrap();
|
||||
raw_map
|
||||
.insert("data".to_string(), Value::Any(Any::String("Old".into())))
|
||||
.unwrap();
|
||||
raw_map
|
||||
.insert("type".to_string(), Value::Any(Any::String("folder".into())))
|
||||
.unwrap();
|
||||
raw_map
|
||||
.insert("index".to_string(), Value::Any(Any::String("a0".into())))
|
||||
.unwrap();
|
||||
raw_map
|
||||
.insert("futureExt".to_string(), Value::Any(Any::Integer(42)))
|
||||
.unwrap();
|
||||
let initial_bytes = raw_doc.encode_update_v1().unwrap();
|
||||
|
||||
let mut table = YjsTableDoc::from_update_v1(
|
||||
WorkspaceDbTableName::Folders.local_doc_id(),
|
||||
WorkspaceDbTableName::Folders.primary_key_field(),
|
||||
WorkspaceDbTableName::Folders.known_fields(),
|
||||
2,
|
||||
&initial_bytes,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(table.soft_delete("f-ext").unwrap().is_some());
|
||||
assert!(table.is_soft_deleted("f-ext").unwrap());
|
||||
assert!(table.get_row::<FolderRow>("f-ext").unwrap().is_none());
|
||||
|
||||
table
|
||||
.upsert_row(&FolderRow {
|
||||
id: "f-ext".into(),
|
||||
parent_id: None,
|
||||
data: "New".into(),
|
||||
folder_type: "folder".into(),
|
||||
index: "a1".into(),
|
||||
})
|
||||
.unwrap();
|
||||
let raw = table.get_raw_row("f-ext").unwrap();
|
||||
assert_eq!(raw["data"], json!("New"));
|
||||
assert_eq!(raw["futureExt"], json!(42));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn millisecond_timestamps_encode_as_float64_never_bigint64_and_roundtrip_as_json_int() {
|
||||
let ts_ms: i64 = 1_795_550_000_000;
|
||||
let mut settings = YjsTableDoc::new(
|
||||
UserdataTableName::Settings.local_doc_id("u1"),
|
||||
UserdataTableName::Settings.primary_key_field(),
|
||||
UserdataTableName::Settings.known_fields(),
|
||||
1,
|
||||
);
|
||||
settings
|
||||
.upsert_row(&SettingsRow {
|
||||
key: "lastSync".into(),
|
||||
value: json!({ "updatedAt": ts_ms }),
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let map = settings.doc.get_map("lastSync").unwrap();
|
||||
match map.get("value") {
|
||||
Some(Value::Any(Any::Object(obj))) => {
|
||||
assert!(
|
||||
matches!(obj.get("updatedAt"), Some(Any::Float64(_))),
|
||||
"expected Float64, got {:?}",
|
||||
obj.get("updatedAt")
|
||||
);
|
||||
}
|
||||
other => panic!("unexpected value: {other:?}"),
|
||||
}
|
||||
|
||||
// y-octo encodes BigInt64 with tag 0x7a (122) followed by big-endian i64 bytes.
|
||||
let encoded = settings.encode_update_v1().unwrap();
|
||||
let mut needle = vec![0x7au8];
|
||||
needle.extend_from_slice(&ts_ms.to_be_bytes());
|
||||
assert!(
|
||||
!encoded
|
||||
.windows(needle.len())
|
||||
.any(|w| w == needle.as_slice()),
|
||||
"encoded Yjs update must not emit lib0 BigInt64 tag 0x7a"
|
||||
);
|
||||
|
||||
let reloaded = YjsTableDoc::from_update_v1(
|
||||
UserdataTableName::Settings.local_doc_id("u1"),
|
||||
UserdataTableName::Settings.primary_key_field(),
|
||||
UserdataTableName::Settings.known_fields(),
|
||||
2,
|
||||
&encoded,
|
||||
)
|
||||
.unwrap();
|
||||
let row = reloaded
|
||||
.get_row::<SettingsRow>("lastSync")
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(row.value["updatedAt"].as_i64(), Some(ts_ms));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn patch_row_fields_preserves_columns_ignores_deleted_or_missing_and_list_rows_skips_corrupt() {
|
||||
let mut folders = YjsTableDoc::new(
|
||||
WorkspaceDbTableName::Folders.local_doc_id(),
|
||||
WorkspaceDbTableName::Folders.primary_key_field(),
|
||||
WorkspaceDbTableName::Folders.known_fields(),
|
||||
1,
|
||||
);
|
||||
folders
|
||||
.upsert_row(&FolderRow {
|
||||
id: "f1".into(),
|
||||
parent_id: Some("p-root".into()),
|
||||
data: "Alpha".into(),
|
||||
folder_type: "folder".into(),
|
||||
index: "a0".into(),
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert!(
|
||||
folders
|
||||
.patch_row_fields("f1", &[("parentId", None)])
|
||||
.unwrap()
|
||||
.is_some()
|
||||
);
|
||||
let updated = folders.get_row::<FolderRow>("f1").unwrap().unwrap();
|
||||
assert_eq!(updated.parent_id, None);
|
||||
assert_eq!(updated.data, "Alpha");
|
||||
assert_eq!(updated.index, "a0");
|
||||
|
||||
// Probe P4: patch_row_fields must not resurrect a soft-deleted row or create a missing row.
|
||||
folders.soft_delete("f1").unwrap();
|
||||
assert!(
|
||||
folders
|
||||
.patch_row_fields("f1", &[("data", Some(json!("Renamed")))])
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
folders
|
||||
.patch_row_fields("never-existed", &[("data", Some(json!("Ghost")))])
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
assert!(folders.is_soft_deleted("f1").unwrap());
|
||||
assert!(folders.get_raw_row("f1").is_none());
|
||||
assert!(folders.get_raw_row("never-existed").is_none());
|
||||
|
||||
// Inject a corrupt row missing required FolderRow fields; list_rows must skip it cleanly.
|
||||
let mut bad = folders.doc.get_or_create_map("f-corrupt").unwrap();
|
||||
bad.insert("id".to_string(), Value::Any(Any::Integer(999)))
|
||||
.unwrap();
|
||||
folders
|
||||
.upsert_row(&FolderRow {
|
||||
id: "f2".into(),
|
||||
parent_id: None,
|
||||
data: "Valid".into(),
|
||||
folder_type: "folder".into(),
|
||||
index: "a1".into(),
|
||||
})
|
||||
.unwrap();
|
||||
let rows = folders.list_rows::<FolderRow>().unwrap();
|
||||
assert_eq!(rows.len(), 1);
|
||||
assert_eq!(rows[0].id, "f2");
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ It uses `resolver = "3"`, edition 2024, and its own `rust-toolchain.toml` (`1.98
|
||||
|
||||
## Workspace boundaries and four-domain guards
|
||||
|
||||
- `packages/frontend/Cargo.toml` lists every client member crate explicitly (`../ui/ui`, `../../blocksuite/crates/doc`, and `../../blocksuite/crates/playground`).
|
||||
- `packages/frontend/Cargo.toml` lists every client member crate explicitly (`../ui/ui`, `../common/store`, `../../blocksuite/crates/doc`, and `../../blocksuite/crates/playground`).
|
||||
Never use directory wildcards that can scan asset directories.
|
||||
- `packages/frontend/Cargo.toml` excludes `native` and `mobile-native`.
|
||||
Those legacy crates remain members of the root `Cargo.toml` workspace.
|
||||
@@ -17,7 +17,7 @@ It uses `resolver = "3"`, edition 2024, and its own `rust-toolchain.toml` (`1.98
|
||||
|
||||
### Performance guardrail and theme/style oracle
|
||||
|
||||
- **`perf/` (`schema.json`, `accepted.json`, `compare-n3.mjs`, `compare-n3.test.mjs`)**: Zero-dependency rolling `N-3` CI comparator with strict schema validation and rerun history anchoring (`--run-id` `created_at` cutoff + pagination). Deterministic byte sizes (`artifacts_bytes.*`) and work counters (non-`_ms` `benchmarks.*`) are hard-gated at strictly `> 10%` (`--fail-on-regression` exits `1`); shared-runner wall-clock timings (`benchmarks.*_ms` at `> 10%`, `ci_wall_ms.*` at `> 10%` and `> 15_000 ms`) are report-only `ADVISORY_SLOWDOWN`. Intentional increases are acknowledged via `{ metric, accepted_value, reason }` ceiling entries in `packages/frontend/perf/accepted.json` (with report-only `stale_acceptances` once the rolling baseline catches up). Unmeasured sub-keys are omitted or `null` (never padded with synthetic `0`s) so newly introduced metrics transition through `BOOTSTRAP`.
|
||||
- **`perf/` (`schema.json`, `accepted.json`, `compare-n3.mjs`, `compare-n3.test.mjs`)**: Zero-dependency rolling `N-3` CI comparator with strict schema validation and rerun history anchoring (`--run-id` `created_at` cutoff + pagination). Deterministic byte sizes (`artifacts_bytes.*`), work counters (non-`_ms` `benchmarks.*`), and unacknowledged `DROPPED` / `--require-n3` `BOOTSTRAP` metrics are hard-gated (`--fail-on-regression` exits `1`); shared-runner wall-clock timings (`benchmarks.*_ms` at `> 10%`, `ci_wall_ms.*` at `> 10%` and `> 15_000 ms`) are report-only `ADVISORY_SLOWDOWN`. Intentional changes are acknowledged in `packages/frontend/perf/accepted.json` via `action: "ceiling"` (`{ metric, accepted_value, reason }`), `action: "bootstrap"` (newly added metrics under `--require-n3`), or `action: "drop"` (retired metrics), with report-only `stale_acceptances` once the rolling `N-3` baseline catches up. Unmeasured sub-keys are omitted or `null` (never padded with synthetic `0`s).
|
||||
|
||||
## Build & verification commands
|
||||
|
||||
@@ -28,6 +28,7 @@ CARGO_ENCODED_RUSTFLAGS="" cargo fmt --all -- --check
|
||||
CARGO_ENCODED_RUSTFLAGS="" cargo clippy --locked --workspace --all-targets --features harness -- -D warnings
|
||||
CARGO_ENCODED_RUSTFLAGS="" cargo check --locked -p ui -p playground --target wasm32-unknown-unknown
|
||||
CARGO_ENCODED_RUSTFLAGS="" cargo check --locked -p blocksuite-playground-doc --no-default-features --target wasm32-unknown-unknown
|
||||
CARGO_ENCODED_RUSTFLAGS="" cargo check --locked -p affine-store --no-default-features --target wasm32-unknown-unknown
|
||||
CARGO_ENCODED_RUSTFLAGS="" cargo test --locked --workspace
|
||||
CARGO_ENCODED_RUSTFLAGS="" cargo test --locked --workspace --features harness
|
||||
CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- render --theme dark --mode page --out frame.png --snapshot frame.json
|
||||
|
||||
Generated
+745
-19
File diff suppressed because it is too large.
Load diff
@@ -2,11 +2,13 @@
|
||||
resolver = "3"
|
||||
members = [
|
||||
"../ui/ui",
|
||||
"../common/store",
|
||||
"../../blocksuite/crates/doc",
|
||||
"../../blocksuite/crates/playground",
|
||||
]
|
||||
default-members = [
|
||||
"../ui/ui",
|
||||
"../common/store",
|
||||
"../../blocksuite/crates/doc",
|
||||
"../../blocksuite/crates/playground",
|
||||
]
|
||||
@@ -23,10 +25,12 @@ anyhow = "1.0.86"
|
||||
async-channel = { version = "2.5", default-features = false }
|
||||
async-task = "4.7"
|
||||
backtrace = "0.3"
|
||||
base64 = "0.22"
|
||||
bitflags = "2.6.0"
|
||||
block2 = "0.6"
|
||||
bytemuck = "1"
|
||||
cbindgen = { version = "0.28.0", default-features = false }
|
||||
chrono = { version = "0.4", default-features = false, features = ["std"] }
|
||||
console_error_panic_hook = "0.1.7"
|
||||
core-foundation = "0.10"
|
||||
core-foundation-sys = "0.8.6"
|
||||
@@ -159,14 +163,17 @@ seahash = "4.1"
|
||||
semver = { version = "1.0", features = ["serde"] }
|
||||
serde = { version = "1.0", features = ["derive", "rc"] }
|
||||
serde_json = { version = "1.0.144", features = ["preserve_order"] }
|
||||
sha2 = "0.10"
|
||||
slotmap = "1.0.6"
|
||||
smallvec = { version = "1.6", features = ["union", "const_new"] }
|
||||
smol_str = { version = "0.3.6", default-features = false, features = ["serde"] }
|
||||
spin = { version = "0.10", default-features = false, features = ["mutex", "spin_mutex", "lock_api"] }
|
||||
sqlx = { version = "0.8.6", default-features = false, features = ["sqlite", "migrate", "runtime-tokio", "chrono"] }
|
||||
strum = { version = "0.28", features = ["derive"] }
|
||||
swash = "0.2.6"
|
||||
taffy = { version = "=0.15.0", default-features = false, features = ["std", "taffy_tree", "flexbox", "grid", "block_layout", "float_layout", "content_size"] }
|
||||
thiserror = "2.0.12"
|
||||
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
|
||||
ttf-parser = "0.25"
|
||||
unicode-bidi = { version = "0.3.18", default-features = false, features = ["hardcoded-data"] }
|
||||
unicode-properties = "=0.1.3"
|
||||
@@ -181,6 +188,7 @@ wasm-bindgen-futures = "0.4"
|
||||
web-sys = "0.3"
|
||||
web-time = "1.1.0"
|
||||
wgpu = { git = "https://github.com/gfx-rs/wgpu", rev = "cddb2f5d80dc0009b2ef6767635140cacf90a007", default-features = false }
|
||||
y-octo = { version = "0.4.0", default-features = false, features = ["session", "large_refs"] }
|
||||
|
||||
[workspace.lints.rust]
|
||||
unexpected_cfgs = { level = "deny" }
|
||||
|
||||
Reference in new issue
Block a user