diff --git a/.github/workflows/native-playground.yml b/.github/workflows/native-playground.yml index 85910b14c8..5146107a17 100644 --- a/.github/workflows/native-playground.yml +++ b/.github/workflows/native-playground.yml @@ -75,7 +75,9 @@ jobs: rm -rf /tmp/np-token-deps - name: Check WebAssembly target - run: cargo check --locked -p ui -p playground --target wasm32-unknown-unknown + 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 headless-linux-and-perf: name: Headless Linux, Web Smoke & Perf @@ -221,10 +223,10 @@ jobs: - name: Check workspace all targets run: cargo check --locked --workspace --all-targets --features harness - - name: Run UI and playground tests (default and harness) + - name: Run UI, doc, and playground tests (default and harness) run: | - cargo test --locked -p ui -p playground - cargo test --locked -p ui -p playground --features harness + cargo test --locked -p ui -p blocksuite-playground-doc -p playground + cargo test --locked -p ui -p blocksuite-playground-doc -p playground --features harness - name: Deterministic Metal headless render and audit run: | @@ -253,3 +255,78 @@ jobs: path: | blocksuite/native-playground/artifacts/macos-run1.png blocksuite/native-playground/artifacts/macos-run1.json + + js-room-coop: + name: JS Room Coop & Rust-JS E2E + runs-on: ubuntu-24.04 + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: 22 + + - name: Enable Corepack and cache Yarn + run: corepack enable + + - name: Cache Yarn + uses: actions/cache@v4 + with: + path: | + .yarn/cache + node_modules + key: ${{ runner.os }}-yarn-np-${{ hashFiles('yarn.lock') }} + restore-keys: | + ${{ runner.os }}-yarn-np- + + - name: Install JS dependencies + run: yarn install --immutable + + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@1.98.1 + + - name: Cache Cargo artifacts + uses: Swatinem/rust-cache@v2 + with: + workspaces: blocksuite/native-playground -> target + key: js-room-coop + + - name: Build bs-relay and bs_doc_driver + working-directory: blocksuite/native-playground + run: cargo build --locked -p blocksuite-playground-doc --bin bs-relay --example bs_doc_driver + + - name: Lint, format, and typecheck JS room sync + run: | + yarn oxlint --deny-warnings \ + blocksuite/framework/sync/src/doc/source.ts \ + blocksuite/framework/sync/src/doc/peer.ts \ + blocksuite/framework/sync/src/__tests__/peer.unit.spec.ts \ + blocksuite/playground/apps/_common/sync/blob/mock-server.ts \ + blocksuite/playground/apps/_common/sync/room/index.ts \ + blocksuite/playground/apps/_common/sync/room/__tests__/room-sync.spec.ts \ + blocksuite/playground/apps/starter/utils/collection.ts \ + blocksuite/playground/vite.config.ts \ + blocksuite/playground/vitest.config.ts + yarn oxfmt --check \ + blocksuite/framework/sync/src/doc/source.ts \ + blocksuite/framework/sync/src/doc/peer.ts \ + blocksuite/framework/sync/src/__tests__/peer.unit.spec.ts \ + blocksuite/playground/apps/_common/sync/blob/mock-server.ts \ + blocksuite/playground/apps/_common/sync/room/index.ts \ + blocksuite/playground/apps/_common/sync/room/__tests__/room-sync.spec.ts \ + blocksuite/playground/apps/starter/utils/collection.ts \ + blocksuite/playground/vite.config.ts \ + blocksuite/playground/vitest.config.ts + ./node_modules/.bin/tsc -b \ + blocksuite/framework/sync/tsconfig.json \ + blocksuite/playground/tsconfig.json + + - name: Run @blocksuite/sync and @blocksuite/playground live Rust-JS E2E tests + env: + BS_RELAY_BIN: ${{ github.workspace }}/blocksuite/native-playground/target/debug/bs-relay + BS_DOC_DRIVER_BIN: ${{ github.workspace }}/blocksuite/native-playground/target/debug/examples/bs_doc_driver + run: | + (cd blocksuite/framework/sync && ../../../node_modules/.bin/vitest run) + (cd blocksuite/playground && ../../node_modules/.bin/vitest run) diff --git a/blocksuite/framework/sync/src/__tests__/peer.unit.spec.ts b/blocksuite/framework/sync/src/__tests__/peer.unit.spec.ts new file mode 100644 index 0000000000..75f4d13cb9 --- /dev/null +++ b/blocksuite/framework/sync/src/__tests__/peer.unit.spec.ts @@ -0,0 +1,210 @@ +import { NoopLogger } from '@blocksuite/global/utils'; +import { describe, expect, it, vi } from 'vitest'; +import * as Y from 'yjs'; + +import { SyncPeer } from '../doc/peer.js'; +import type { DocSource } from '../doc/source.js'; +import { SharedPriorityTarget } from '../utils/async-queue.js'; + +describe('SyncPeer finishPull and disconnect handling', () => { + it('calls finishPull even when diffToStorage is empty [0, 0]', async () => { + const doc = new Y.Doc({ guid: 'doc:empty-handshake' }); + const remote = new Y.Doc({ guid: 'doc:empty-handshake' }); + + const finishPull = vi.fn(); + const push = vi.fn(); + const source: DocSource = { + name: 'mock-room', + pull: async () => ({ + data: Y.encodeStateAsUpdate(remote), + state: Y.encodeStateVector(remote), + }), + finishPull, + push, + subscribe: () => () => {}, + }; + + const peer = new SyncPeer( + doc, + source, + new SharedPriorityTarget(), + new NoopLogger() + ); + + await vi.waitFor(() => { + expect(finishPull).toHaveBeenCalledTimes(1); + }); + + const [calledDocId, diff] = finishPull.mock.calls[0] as [ + string, + Uint8Array, + ]; + expect(calledDocId).toBe('doc:empty-handshake'); + expect(Array.from(diff)).toEqual([0, 0]); + expect(push).not.toHaveBeenCalled(); + + peer.stop(); + }); + + it('aborts connectDoc cleanly when pull rejects on disconnect', async () => { + const doc = new Y.Doc({ guid: 'doc:disconnect-reject' }); + let pullCalls = 0; + const finishPull = vi.fn(); + + const source: DocSource = { + name: 'mock-disconnect-room', + pull: async () => { + pullCalls += 1; + throw new Error('socket closed'); + }, + finishPull, + push: vi.fn(), + subscribe: () => () => {}, + }; + + const peer = new SyncPeer( + doc, + source, + new SharedPriorityTarget(), + new NoopLogger() + ); + + await vi.waitFor(() => { + expect(pullCalls).toBeGreaterThanOrEqual(1); + }); + + expect(finishPull).not.toHaveBeenCalled(); + peer.stop(); + }); + + it('captures local edits made while finishPull is pending without echoing pulled data', async () => { + const doc = new Y.Doc({ guid: 'doc:edit-during-finish-pull' }); + const remote = new Y.Doc({ guid: 'doc:edit-during-finish-pull' }); + remote.getText('t').insert(0, 'seed'); + + let resolveFinishPull!: () => void; + let finishPullStarted!: () => void; + const finishPullStartedPromise = new Promise(resolve => { + finishPullStarted = resolve; + }); + + const pushedUpdates: Uint8Array[] = []; + const source: DocSource = { + name: 'mock-room', + pull: async () => ({ + data: Y.encodeStateAsUpdate(remote), + state: Y.encodeStateVector(remote), + }), + finishPull: async (_docId, diff) => { + if ( + !( + diff.byteLength === 0 || + (diff.byteLength === 2 && diff[0] === 0 && diff[1] === 0) + ) + ) { + Y.applyUpdate(remote, diff); + } + finishPullStarted(); + await new Promise(resolve => { + resolveFinishPull = resolve; + }); + }, + push: async (_docId, data) => { + pushedUpdates.push(data); + Y.applyUpdate(remote, data); + }, + subscribe: () => () => {}, + }; + + const peer = new SyncPeer( + doc, + source, + new SharedPriorityTarget(), + new NoopLogger() + ); + + await finishPullStartedPromise; + // Mutate locally BEFORE finishPull resolves. + doc.getText('t').insert(doc.getText('t').length, 'x'); + resolveFinishPull(); + + await vi.waitFor(() => { + expect(remote.getText('t').toString()).toBe('seedx'); + }); + expect(pushedUpdates.length).toBeGreaterThanOrEqual(1); + + peer.stop(); + }); + + it('buffers incoming onPush updates that arrive before a subdoc finishes pull', async () => { + const rootDoc = new Y.Doc({ guid: 'root:pending-buffer' }); + const subdoc = new Y.Doc({ guid: 'sub:pending-buffer' }); + const remoteSubdoc = new Y.Doc({ guid: 'sub:pending-buffer' }); + + let emitStorageUpdate!: (id: string, data: Uint8Array) => void; + let resolveSubdocPull!: (value: { + data: Uint8Array; + state: Uint8Array; + }) => void; + let subdocPullStarted!: () => void; + const subdocPullStartedPromise = new Promise(resolve => { + subdocPullStarted = resolve; + }); + + const source: DocSource = { + name: 'mock-room', + pull: async docId => { + if (docId === rootDoc.guid) { + return { + data: Y.encodeStateAsUpdate(new Y.Doc()), + state: Y.encodeStateVector(new Y.Doc()), + }; + } + subdocPullStarted(); + return new Promise(resolve => { + resolveSubdocPull = resolve; + }); + }, + finishPull: async () => {}, + push: async () => {}, + subscribe: cb => { + emitStorageUpdate = cb; + return () => {}; + }, + }; + + const peer = new SyncPeer( + rootDoc, + source, + new SharedPriorityTarget(), + new NoopLogger() + ); + + await vi.waitFor(() => { + expect(peer.state.connectedDocs.has(rootDoc.guid)).toBe(true); + }); + + // Attach subdoc so SyncPeer begins pulling it. + rootDoc.getMap('spaces').set(subdoc.guid, subdoc); + await subdocPullStartedPromise; + + // Deliver a remote push for subdoc BEFORE its pull resolves. + remoteSubdoc.getText('t').insert(0, 'buffered-early'); + emitStorageUpdate(subdoc.guid, Y.encodeStateAsUpdate(remoteSubdoc)); + + // Give pull loop a tick to consume and buffer the update. + await new Promise(resolve => setTimeout(resolve, 20)); + + // Resolve subdoc pull with empty initial state; buffered push must still apply! + resolveSubdocPull({ + data: Y.encodeStateAsUpdate(new Y.Doc()), + state: Y.encodeStateVector(new Y.Doc()), + }); + + await vi.waitFor(() => { + expect(subdoc.getText('t').toString()).toBe('buffered-early'); + }); + + peer.stop(); + }); +}); diff --git a/blocksuite/framework/sync/src/doc/peer.ts b/blocksuite/framework/sync/src/doc/peer.ts index a8712bcbb4..d3a3965b7b 100644 --- a/blocksuite/framework/sync/src/doc/peer.ts +++ b/blocksuite/framework/sync/src/doc/peer.ts @@ -114,6 +114,7 @@ export class SyncPeer { readonly state: { connectedDocs: Map; + pendingIncomingUpdates: Map; pushUpdatesQueue: PriorityAsyncQueue<{ id: string; data: Uint8Array[]; @@ -127,6 +128,7 @@ export class SyncPeer { subdocsLoadQueue: PriorityAsyncQueue<{ id: string; doc: Doc }>; } = { connectedDocs: new Map(), + pendingIncomingUpdates: new Map(), pushUpdatesQueue: new PriorityAsyncQueue([], this.priorityTarget), pushingUpdate: false, pullUpdatesQueue: new PriorityAsyncQueue([], this.priorityTarget), @@ -173,18 +175,36 @@ export class SyncPeer { applyUpdate(doc, docData, 'load'); } - // diff root doc and in-storage, save updates to pendingUpdates - this.state.pushUpdatesQueue.push({ - id: doc.guid, - data: [encodeStateAsUpdate(doc, inStorageState)], - }); + // diff doc and in-storage BEFORE attaching handleYDocUpdates so pulled data is never echoed + const diffToStorage = encodeStateAsUpdate(doc, inStorageState); this.state.connectedDocs.set(doc.guid, doc); - - // start listen root doc changes doc.on('update', this.handleYDocUpdates); - // mark rootDoc as loaded + const buffered = this.state.pendingIncomingUpdates.get(doc.guid); + if (buffered && buffered.length > 0) { + this.state.pendingIncomingUpdates.delete(doc.guid); + for (const update of buffered) { + applyUpdate(doc, update, this.name); + } + } + + try { + if (this.source.finishPull) { + await this.source.finishPull(doc.guid, diffToStorage); + throwIfAborted(abort); + } else { + this.state.pushUpdatesQueue.push({ + id: doc.guid, + data: [diffToStorage], + }); + } + } catch (err) { + this.disconnectDoc(doc); + throw err; + } + + // mark doc as loaded doc.emit('sync', [true, doc]); this.updateSyncStatus(); @@ -193,11 +213,13 @@ export class SyncPeer { disconnectDoc(doc: Doc) { doc.off('update', this.handleYDocUpdates); this.state.connectedDocs.delete(doc.guid); + this.state.pendingIncomingUpdates.delete(doc.guid); this.updateSyncStatus(); } initState() { this.state.connectedDocs.clear(); + this.state.pendingIncomingUpdates.clear(); this.state.pushUpdatesQueue.clear(); this.state.pullUpdatesQueue.clear(); this.state.subdocsLoadQueue.clear(); @@ -285,6 +307,13 @@ export class SyncPeer { const subdoc = this.state.connectedDocs.get(id); if (subdoc) { applyUpdate(subdoc, data, this.name); + } else { + const pending = this.state.pendingIncomingUpdates.get(id); + if (pending) { + pending.push(data); + } else { + this.state.pendingIncomingUpdates.set(id, [data]); + } } } this.updateSyncStatus(); diff --git a/blocksuite/framework/sync/src/doc/source.ts b/blocksuite/framework/sync/src/doc/source.ts index b4d7f52bb9..4707db43a1 100644 --- a/blocksuite/framework/sync/src/doc/source.ts +++ b/blocksuite/framework/sync/src/doc/source.ts @@ -11,6 +11,7 @@ export interface DocSource { | Promise<{ data: Uint8Array; state?: Uint8Array } | null> | { data: Uint8Array; state?: Uint8Array } | null; + finishPull?(docId: string, diffToStorage: Uint8Array): Promise | void; push(docId: string, data: Uint8Array): Promise | void; /** diff --git a/blocksuite/native-playground/AGENTS.md b/blocksuite/native-playground/AGENTS.md index a88c32c80b..c356a85116 100644 --- a/blocksuite/native-playground/AGENTS.md +++ b/blocksuite/native-playground/AGENTS.md @@ -6,6 +6,7 @@ This document records the active engineering invariants enforced in CI today alo ### Workspace boundaries - `crates/ui`: Single fused internal GPU UI library (vendored once without upstream sync hooks, zero internal `proc-macro = true` crates, zero external UI-kit dependencies). It knows **nothing** about BlockSuite or AFFiNE (`scripts/check-invariants.sh` rejects `blocksuite` and `affine` inside `crates/ui`) and embeds zero fonts (fonts are registered by the application via `cx.text_system().add_fonts(...)`). +- `crates/doc` (`blocksuite-playground-doc`) & `bs-relay`: Pure CRDT document engine and binary room sync relay (`#![forbid(unsafe_code)]`, zero GUI/platform dependencies — `scripts/check-invariants.sh` rejects `ui`, `wgpu`, `objc2`, and `web-sys` in `crates/doc/Cargo.toml`) built on `y-octo 0.3.0`. Preserves 53-bit `clientId` (`1..=2^53 - 1`), complete flavour schema defaults (0 JS writeback updates on initial load), top-level Awareness `color` alongside `user` and `selectionV2`, deterministic `now_ms`-driven undo/awareness clocks, WebSocket-only `seed-claim` / `seed-claim-result` single-winner arbitration (keyed by `seed:`), `?ws=` relay origin forwarding with permissive blob CORS headers, and `wasm32-unknown-unknown` compatibility under `--no-default-features`. - `crates/playground`: Application layer owning the shipping `PlaygroundView`, the tracked repository `Inter` base font registration, the native macOS desktop entry (`native-playground`), the WebAssembly canvas entry (`wasm_main`), and the deterministic headless verification CLI (`bs-harness`). - `unexpected_cfgs = "deny"` is enforced workspace-wide in `Cargo.toml`; dead upstream feature gates are forbidden. @@ -30,7 +31,6 @@ This document records the active engineering invariants enforced in CI today alo ## Planned Contracts (upcoming crates & features) -- **`crates/doc` & `bs-relay`**: Pure CRDT document model (`#![forbid(unsafe_code)]`, zero GUI dependencies) built on `y-octo`, preserving 53-bit `clientId` (`1..=2^53 - 1`), complete flavour schema defaults (0 JS writeback updates on initial load), and top-level Awareness `color` alongside `user` and `selectionV2`. - **Editor & whiteboard rendering**: `BlockFlow`, `RichParagraph`, `EditorSession`, and world-space content transforms/masks (implemented end-to-end in the GPU shaders) separating world-space document/whiteboard geometry from screen-space GPUI chrome. - **Variable-font slant axis**: OpenType `'slnt'` (`FontStyle::Italic`) variation-axis shaping and rasterization will be wired alongside rich inline marks. @@ -40,10 +40,11 @@ Always clear inherited root rustflags: ```sh CARGO_ENCODED_RUSTFLAGS="" cargo fmt --all -- --check -CARGO_ENCODED_RUSTFLAGS="" cargo clippy --workspace --all-targets --features harness -- -D warnings -CARGO_ENCODED_RUSTFLAGS="" cargo check -p ui -p playground --target wasm32-unknown-unknown -CARGO_ENCODED_RUSTFLAGS="" cargo test --workspace -CARGO_ENCODED_RUSTFLAGS="" cargo test --workspace --features harness +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 test --locked --workspace +CARGO_ENCODED_RUSTFLAGS="" cargo test --locked --workspace --features harness ./scripts/check-invariants.sh node --test perf/compare-n3.test.mjs node tokens/extract-tokens.mjs --check diff --git a/blocksuite/native-playground/Cargo.lock b/blocksuite/native-playground/Cargo.lock index ca8f042b72..fde04e1bca 100644 --- a/blocksuite/native-playground/Cargo.lock +++ b/blocksuite/native-playground/Cargo.lock @@ -17,6 +17,19 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "const-random", + "once_cell", + "version_check", + "zerocopy", +] + [[package]] name = "aho-corasick" version = "1.1.5" @@ -41,12 +54,71 @@ dependencies = [ "libc", ] +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + [[package]] name = "anyhow" version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" +dependencies = [ + "derive_arbitrary", +] + [[package]] name = "arrayref" version = "0.3.9" @@ -80,17 +152,90 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "async-lock" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f" +dependencies = [ + "event-listener", + "event-listener-strategy", + "loom", + "pin-project-lite", +] + [[package]] name = "async-task" version = "4.7.1" source = "git+https://github.com/zed-industries/async-task.git?rev=015845a19fc31752c02367567d3b8900a406f9da#015845a19fc31752c02367567d3b8900a406f9da" +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + [[package]] name = "autocfg" version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "base64 0.22.1", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sha1", + "sync_wrapper", + "tokio", + "tokio-tungstenite 0.29.0", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + [[package]] name = "backtrace" version = "0.3.77" @@ -103,7 +248,7 @@ dependencies = [ "miniz_oxide 0.9.1", "object", "rustc-demangle", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -112,6 +257,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "bit-set" version = "0.11.1" @@ -126,6 +277,10 @@ name = "bit-vec" version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72503af1e72be411d74ca45cd6b309878fcb35354e252fc2a3a8bda3a97082a0" +dependencies = [ + "borsh", + "serde", +] [[package]] name = "bitflags" @@ -139,6 +294,15 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "block2" version = "0.6.2" @@ -148,6 +312,51 @@ dependencies = [ "objc2", ] +[[package]] +name = "blocksuite-playground-doc" +version = "0.1.0" +dependencies = [ + "axum", + "clap", + "futures-util", + "proptest", + "rand 0.9.5", + "rand_chacha", + "reqwest", + "serde", + "serde_json", + "thiserror", + "tokio", + "tokio-tungstenite 0.26.2", + "tracing", + "tracing-subscriber", + "y-octo", +] + +[[package]] +name = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "bumpalo" version = "3.20.4" @@ -186,6 +395,12 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + [[package]] name = "cbindgen" version = "0.28.0" @@ -226,6 +441,57 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + +[[package]] +name = "clap" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "844c5c0b65be192cb68d570cca1b21a6444431d24e39c084dc0336177015337c" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + [[package]] name = "codespan-reporting" version = "0.13.1" @@ -243,6 +509,12 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + [[package]] name = "concurrent-queue" version = "2.5.0" @@ -262,6 +534,26 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "const-random" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359" +dependencies = [ + "const-random-macro", +] + +[[package]] +name = "const-random-macro" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e" +dependencies = [ + "getrandom 0.2.17", + "once_cell", + "tiny-keccak", +] + [[package]] name = "convert_case" version = "0.10.0" @@ -323,6 +615,12 @@ dependencies = [ "libc", ] +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + [[package]] name = "core_maths" version = "0.1.1" @@ -356,6 +654,24 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + [[package]] name = "crc32fast" version = "1.5.5" @@ -377,6 +693,16 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "ctor" version = "1.0.14" @@ -387,12 +713,29 @@ dependencies = [ "linktime-proc-macro", ] +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + [[package]] name = "data-url" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" +[[package]] +name = "derive_arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "derive_more" version = "2.1.1" @@ -415,6 +758,16 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + [[package]] name = "dirs" version = "6.0.0" @@ -535,6 +888,7 @@ version = "5.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" dependencies = [ + "loom", "parking", "pin-project-lite", ] @@ -610,6 +964,12 @@ dependencies = [ "spin 0.9.9", ] +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + [[package]] name = "foldhash" version = "0.2.0" @@ -792,6 +1152,41 @@ dependencies = [ "slab", ] +[[package]] +name = "generator" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6c6a73cd1aa4f4f00c02b109fa55d3a9d6ecc2fc4f53177b74ed6ee23b0c53" +dependencies = [ + "cc", + "libc", + "log", + "rustversion", + "windows-core 0.100.0", + "windows-sys", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -815,6 +1210,7 @@ dependencies = [ "cfg-if", "libc", "r-efi 6.0.0", + "rand_core 0.10.1", ] [[package]] @@ -960,6 +1356,95 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + [[package]] name = "icu_collections" version = "2.4.0" @@ -1135,7 +1620,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" dependencies = [ "byteorder-lite", - "quick-error", + "quick-error 2.0.1", ] [[package]] @@ -1156,6 +1641,18 @@ dependencies = [ "serde_core", ] +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itertools" version = "0.14.0" @@ -1186,7 +1683,7 @@ dependencies = [ "portable-atomic-util", "serde_core", "wasm-bindgen", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -1312,7 +1809,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" dependencies = [ "cfg-if", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -1381,6 +1878,21 @@ version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" +[[package]] +name = "loom" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1611ddbf89dc6ae42cfbd51fc207836140130257646eab8d6d2fb16577db2d2" +dependencies = [ + "cfg-if", + "generator", + "scoped-tls", + "serde", + "serde_json", + "tracing", + "tracing-subscriber", +] + [[package]] name = "lyon" version = "1.0.19" @@ -1455,6 +1967,21 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc04a4c58212d57930a24bf47d3fa87485264a3a054e9c10e042eb373573ad3c" +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + [[package]] name = "memchr" version = "2.8.3" @@ -1470,6 +1997,12 @@ dependencies = [ "libc", ] +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -1490,6 +2023,17 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "wasi", + "windows-sys", +] + [[package]] name = "moxcms" version = "0.8.1" @@ -1545,6 +2089,24 @@ dependencies = [ "jni-sys 0.3.1", ] +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -1717,6 +2279,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "option-ext" version = "0.2.0" @@ -1729,6 +2297,7 @@ version = "5.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab" dependencies = [ + "arbitrary", "num-traits", ] @@ -1737,6 +2306,9 @@ name = "parking" version = "2.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" +dependencies = [ + "loom", +] [[package]] name = "parking_lot" @@ -1758,7 +2330,7 @@ dependencies = [ "libc", "redox_syscall", "smallvec", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -1835,6 +2407,7 @@ name = "playground" version = "0.1.0" dependencies = [ "anyhow", + "blocksuite-playground-doc", "console_error_panic_hook", "image", "serde", @@ -1926,6 +2499,15 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa" +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit 0.25.20+spec-1.1.0", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -1941,12 +2523,38 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" +[[package]] +name = "proptest" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" +dependencies = [ + "bit-set", + "bit-vec", + "bitflags 2.13.2", + "chacha20", + "core_detect", + "num-traits", + "rand 0.10.4", + "rand_xorshift", + "regex-syntax", + "rusty-fork", + "tempfile", + "unarray", +] + [[package]] name = "pxfm" version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + [[package]] name = "quick-error" version = "2.0.1" @@ -1981,7 +2589,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" dependencies = [ "rand_chacha", - "rand_core", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "getrandom 0.4.3", + "rand_core 0.10.1", ] [[package]] @@ -1991,7 +2609,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.9.5", ] [[package]] @@ -2003,6 +2621,21 @@ dependencies = [ "getrandom 0.3.4", ] +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_xorshift" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf" +dependencies = [ + "rand_core 0.10.1", +] + [[package]] name = "rangemap" version = "1.8.0" @@ -2103,6 +2736,38 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "resvg" version = "0.46.0" @@ -2190,6 +2855,18 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "rusty-fork" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" +dependencies = [ + "fnv", + "quick-error 1.2.3", + "tempfile", + "wait-timeout", +] + [[package]] name = "rustybuzz" version = "0.20.1" @@ -2208,6 +2885,18 @@ dependencies = [ "unicode-script", ] +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "ryu-js" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04d056b875a9d2e6cb9a61d127afee9ac5999b9f87bcb32079d1318e505be714" + [[package]] name = "same-file" version = "1.0.6" @@ -2217,6 +2906,12 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + [[package]] name = "scopeguard" version = "1.2.0" @@ -2290,6 +2985,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + [[package]] name = "serde_spanned" version = "0.6.9" @@ -2299,12 +3005,54 @@ dependencies = [ "serde", ] +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + [[package]] name = "shlex" version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + [[package]] name = "simd-adler32" version = "0.3.10" @@ -2373,9 +3121,20 @@ version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eeb7109d23f319619d4cc0de5464613c8b7b1a09db2774a58101459cf6be2f10" dependencies = [ + "borsh", "serde_core", ] +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys", +] + [[package]] name = "spin" version = "0.9.9" @@ -2424,6 +3183,12 @@ dependencies = [ "float-cmp", ] +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "strum" version = "0.28.0" @@ -2494,6 +3259,15 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + [[package]] name = "synstructure" version = "0.14.0" @@ -2567,6 +3341,24 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tiny-keccak" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" +dependencies = [ + "crunchy", +] + [[package]] name = "tiny-skia" version = "0.11.4" @@ -2616,7 +3408,49 @@ version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ + "bytes", + "libc", + "mio", "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.26.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9daff607c6d2bf6c16fd681ccb7eecc83e4e2cdc1ca067ffaadfca5de7f084" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite 0.26.2", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite 0.29.0", ] [[package]] @@ -2627,8 +3461,8 @@ checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" dependencies = [ "serde", "serde_spanned", - "toml_datetime", - "toml_edit", + "toml_datetime 0.6.11", + "toml_edit 0.22.27", ] [[package]] @@ -2640,6 +3474,15 @@ dependencies = [ "serde", ] +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + [[package]] name = "toml_edit" version = "0.22.27" @@ -2649,9 +3492,30 @@ dependencies = [ "indexmap", "serde", "serde_spanned", - "toml_datetime", + "toml_datetime 0.6.11", "toml_write", - "winnow", + "winnow 0.7.15", +] + +[[package]] +name = "toml_edit" +version = "0.25.20+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e76360e201d6dbd6583e17795ba71a88f47365a9139c8450a7979c32303b8e73" +dependencies = [ + "indexmap", + "toml_datetime 1.1.3+spec-1.1.0", + "toml_parser", + "winnow 1.0.5", +] + +[[package]] +name = "toml_parser" +version = "1.1.6+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31" +dependencies = [ + "winnow 1.0.5", ] [[package]] @@ -2660,6 +3524,120 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags 2.13.2", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + [[package]] name = "ttf-parser" version = "0.25.1" @@ -2669,6 +3647,45 @@ dependencies = [ "core_maths", ] +[[package]] +name = "tungstenite" +version = "0.26.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4793cb5e56680ecbb1d843515b23b6de9a75eb04b66643e256a396d43be33c13" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1", + "thiserror", + "utf-8", +] + +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1", + "thiserror", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "ui" version = "0.1.0" @@ -2722,7 +3739,7 @@ dependencies = [ "pathfinder_geometry", "pin-project", "pollster", - "rand", + "rand 0.9.5", "raw-window-handle", "regex", "resvg", @@ -2756,6 +3773,12 @@ dependencies = [ "zed-font-kit", ] +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + [[package]] name = "unicode-bidi" version = "0.3.18" @@ -2834,7 +3857,7 @@ version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e419dff010bb12512b0ae9e3d2f318dfbdf0167fde7eb05465134d4e8756076f" dependencies = [ - "base64", + "base64 0.22.1", "data-url", "flate2", "fontdb", @@ -2855,6 +3878,12 @@ dependencies = [ "xmlwriter", ] +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + [[package]] name = "utf8_iter" version = "1.1.0" @@ -2864,6 +3893,12 @@ dependencies = [ "utf_types", ] +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "utf_types" version = "1.0.0" @@ -2882,12 +3917,27 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + [[package]] name = "version_check" version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + [[package]] name = "waker-fn" version = "1.2.0" @@ -2904,6 +3954,21 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + [[package]] name = "wasip2" version = "1.0.4+wasi-0.2.12" @@ -3140,8 +4205,8 @@ dependencies = [ "wgpu-sync", "wgpu-types", "windows", - "windows-core", - "windows-result", + "windows-core 0.62.2", + "windows-result 0.4.1", ] [[package]] @@ -3220,7 +4285,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" dependencies = [ "windows-collections", - "windows-core", + "windows-core 0.62.2", "windows-future", "windows-numerics", ] @@ -3231,7 +4296,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" dependencies = [ - "windows-core", + "windows-core 0.62.2", ] [[package]] @@ -3240,11 +4305,24 @@ version = "0.62.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" dependencies = [ - "windows-implement", - "windows-interface", - "windows-link", - "windows-result", - "windows-strings", + "windows-implement 0.60.2", + "windows-interface 0.59.3", + "windows-link 0.2.1", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + +[[package]] +name = "windows-core" +version = "0.100.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "803590c6856f51d15fa2e9fabe4f4703122c8737f72ef2741b4ac09d4c2192f5" +dependencies = [ + "windows-implement 0.100.0", + "windows-interface 0.100.0", + "windows-link 0.100.0", + "windows-result 0.100.0", + "windows-strings 0.100.0", ] [[package]] @@ -3253,8 +4331,8 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" dependencies = [ - "windows-core", - "windows-link", + "windows-core 0.62.2", + "windows-link 0.2.1", "windows-threading", ] @@ -3269,6 +4347,17 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "windows-implement" +version = "0.100.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bc1bc82e5a1b1a4d7255861b07881a0407b552f50a4d8543c0c7276fa96f6e8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "windows-interface" version = "0.59.3" @@ -3280,20 +4369,37 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "windows-interface" +version = "0.100.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3f7005c3b757b9b82c2f40c0e71094ff1080adddaf3e8b6ce99b545d3c48796" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-link" +version = "0.100.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b39de7c7fe78858b0144c50c3fc000bab3be17d5e9b85b1053871693c7f7415" + [[package]] name = "windows-numerics" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" dependencies = [ - "windows-core", - "windows-link", + "windows-core 0.62.2", + "windows-link 0.2.1", ] [[package]] @@ -3302,7 +4408,16 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" dependencies = [ - "windows-link", + "windows-link 0.2.1", +] + +[[package]] +name = "windows-result" +version = "0.100.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44873a1ef61c85d5e2991db91fe656cfcf0731097e00dff1ac860f1cb3b752a0" +dependencies = [ + "windows-link 0.100.0", ] [[package]] @@ -3311,7 +4426,16 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" dependencies = [ - "windows-link", + "windows-link 0.2.1", +] + +[[package]] +name = "windows-strings" +version = "0.100.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a70b590c684f1d2854f74999896f7c0558f1bdde62f599088599e20ea1d2f60" +dependencies = [ + "windows-link 0.100.0", ] [[package]] @@ -3320,7 +4444,7 @@ version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" dependencies = [ - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -3329,7 +4453,7 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" dependencies = [ - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -3341,6 +4465,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] + [[package]] name = "wio" version = "0.2.2" @@ -3374,6 +4507,28 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" +[[package]] +name = "y-octo" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e381655b2334e81e3088ff85d021c31a2ec950dac0ae96b538aea674321e7d3c" +dependencies = [ + "ahash", + "arbitrary", + "async-lock", + "byteorder", + "indexmap", + "log", + "loom", + "nom", + "ordered-float", + "ryu-js", + "serde", + "serde_json", + "smol_str", + "thiserror", +] + [[package]] name = "yazi" version = "0.2.2" diff --git a/blocksuite/native-playground/Cargo.toml b/blocksuite/native-playground/Cargo.toml index 7e9edf4d6d..a18d8ab90d 100644 --- a/blocksuite/native-playground/Cargo.toml +++ b/blocksuite/native-playground/Cargo.toml @@ -2,9 +2,10 @@ resolver = "3" members = [ "crates/ui", + "crates/doc", "crates/playground", ] -default-members = ["crates/ui", "crates/playground"] +default-members = ["crates/ui", "crates/doc", "crates/playground"] [workspace.package] version = "0.1.0" diff --git a/blocksuite/native-playground/crates/doc/Cargo.toml b/blocksuite/native-playground/crates/doc/Cargo.toml new file mode 100644 index 0000000000..171ce92043 --- /dev/null +++ b/blocksuite/native-playground/crates/doc/Cargo.toml @@ -0,0 +1,49 @@ +[package] +name = "blocksuite-playground-doc" +version.workspace = true +edition.workspace = true +publish.workspace = true +license.workspace = true + +[lints] +workspace = true + +[features] +default = ["server"] +server = [ + "dep:axum", + "dep:clap", + "dep:futures-util", + "dep:tokio", + "dep:tracing", + "dep:tracing-subscriber", +] + +[dependencies] +serde.workspace = true +serde_json = { workspace = true, features = ["float_roundtrip"] } +thiserror.workspace = true +y-octo = { version = "0.3.0", default-features = false, features = ["session"] } + +[target.'cfg(not(target_family = "wasm"))'.dependencies] +axum = { version = "0.8", features = ["ws"], optional = true } +clap = { version = "4", features = ["derive"], optional = true } +futures-util = { version = "0.3", optional = true } +rand.workspace = true +tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync", "time"], optional = true } +tracing = { version = "0.1", optional = true } +tracing-subscriber = { version = "0.3", features = ["env-filter"], optional = true } + +[dev-dependencies] +proptest = "1" +rand.workspace = true +rand_chacha = "0.9" + +[target.'cfg(not(target_family = "wasm"))'.dev-dependencies] +tokio-tungstenite = "0.26" +reqwest = { version = "0.12", default-features = false, features = ["json"] } + +[[bin]] +name = "bs-relay" +path = "src/bin/bs_relay.rs" +required-features = ["server"] diff --git a/blocksuite/native-playground/crates/doc/examples/bs_doc_driver.rs b/blocksuite/native-playground/crates/doc/examples/bs_doc_driver.rs new file mode 100644 index 0000000000..fd85d04433 --- /dev/null +++ b/blocksuite/native-playground/crates/doc/examples/bs_doc_driver.rs @@ -0,0 +1,807 @@ +#![forbid(unsafe_code)] + +//! Interactive JSON-line driver wrapping `crates/doc` (`WorkspaceSession` + `RoomAwareness` + +//! WebSocket client) for live Rust <-> JS Vitest room collaboration tests. + +use std::io::{self, BufRead, Write}; + +use blocksuite_playground_doc::{ + awareness::{ + AWARENESS_EXPIRE_TIMEOUT_MS, AwarenessPayload, RoomAwareness, TextRangePoint, + TextSelectionState, + }, + schema::{BlockSpec, ConnectorEndpointSpec, ListType, ParagraphType, SurfaceElementSpec}, + session::WorkspaceSession, + wire::{ + DocSyncState, RoomBinaryFrame, RoomControlFrame, decode_binary_frame, decode_control_frame, + encode_binary_frame, + }, +}; +use clap::Parser; +use futures_util::{SinkExt, StreamExt}; +use serde::Deserialize; +use serde_json::{Value as JsonValue, json}; +use tokio::sync::mpsc; +use tokio_tungstenite::{connect_async, tungstenite::Message as WsMsg}; +use y_octo::{Any, DocMessage, SessionValue, StateVector, TextAttributes}; + +#[derive(Debug, Parser)] +struct Args { + #[arg(long)] + relay_http: String, + #[arg(long)] + room: String, + #[arg(long)] + client_id: u64, +} + +#[derive(Debug, Deserialize)] +#[serde(tag = "cmd", rename_all = "snake_case")] +enum Command { + SeedFullSchema { + page_id: String, + title: String, + }, + SyncAll, + Reconnect, + InsertText { + page_id: String, + block_id: String, + index: u64, + text: String, + now_ms: u64, + }, + RemoveText { + page_id: String, + block_id: String, + index: u64, + len: u64, + now_ms: u64, + }, + FormatText { + page_id: String, + block_id: String, + index: u64, + len: u64, + bold: bool, + now_ms: u64, + }, + ReorderChild { + page_id: String, + parent_id: String, + child_id: String, + new_index: u64, + now_ms: u64, + }, + UpdateShapeXywh { + page_id: String, + surface_id: String, + element_id: String, + xywh: String, + now_ms: u64, + }, + UpdateConnectorMode { + page_id: String, + surface_id: String, + element_id: String, + mode: i32, + now_ms: u64, + }, + SetAwareness { + name: String, + color: String, + store_key: String, + block_id: String, + #[serde(default)] + index: u64, + #[serde(default)] + length: u64, + now_ms: u64, + }, + TickAwareness { + now_ms: u64, + }, + UploadBlob { + key: String, + bytes: Vec, + }, + FetchBlob { + key: String, + }, + Drain { + wait_ms: u64, + }, + ExportState { + page_id: String, + }, + Quit, +} + +type WsStream = + tokio_tungstenite::WebSocketStream>; + +async fn connect_room(relay_http: &str, room: &str) -> WsStream { + let ws_base = relay_http + .replacen("http://", "ws://", 1) + .replacen("https://", "wss://", 1); + let url = format!("{ws_base}/native-sync/rooms/{room}"); + let (stream, _) = connect_async(&url).await.expect("connect ws"); + stream +} + +async fn apply_incoming_frame( + ws_session: &mut WorkspaceSession, + awareness: &mut RoomAwareness, + ws: &mut WsStream, + bytes: &[u8], +) { + let Ok(frame) = decode_binary_frame(bytes) else { + return; + }; + match frame { + RoomBinaryFrame::Doc { + doc_id, + message: DocMessage::Update(update), + } => { + if update.is_empty() || update == [0, 0] { + return; + } + if doc_id == ws_session.room() { + if let Ok(res) = ws_session.apply_root_update_v1(&update) { + for out in res.outbound_updates { + let f = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id: doc_id.clone(), + message: DocMessage::Update(out), + }) + .unwrap(); + let _ = ws.send(WsMsg::Binary(f.into())).await; + } + } + } else if let Ok(page) = ws_session.ensure_page(&doc_id) + && let Ok(res) = page.apply_remote_update_v1(&update) + { + for out in res.outbound_updates { + let f = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id: doc_id.clone(), + message: DocMessage::Update(out), + }) + .unwrap(); + let _ = ws.send(WsMsg::Binary(f.into())).await; + } + } + } + RoomBinaryFrame::Awareness(payload) => { + let _ = awareness.apply_update(&payload, 1_000); + } + _ => {} + } +} + +async fn sync_single_doc( + ws: &mut WsStream, + ws_session: &mut WorkspaceSession, + awareness: &mut RoomAwareness, + doc_id: &str, +) { + let mut state = DocSyncState::new(doc_id); + let sv = ws_session.encode_state_vector_v1(doc_id).unwrap(); + let step1 = state.begin_pull(sv); + ws.send(WsMsg::Binary(encode_binary_frame(&step1).unwrap().into())) + .await + .unwrap(); + + let hub_sv = loop { + if let WsMsg::Binary(b) = ws.next().await.unwrap().unwrap() { + match decode_binary_frame(&b).unwrap() { + RoomBinaryFrame::Doc { + doc_id: d, + message: DocMessage::Step2(diff), + } if d == doc_id => { + if !(diff.is_empty() || diff == [0, 0]) { + if doc_id == ws_session.room() { + ws_session.apply_root_update_v1(&diff).unwrap(); + } else { + ws_session + .ensure_page(doc_id) + .unwrap() + .apply_remote_update_v1(&diff) + .unwrap(); + } + } + if let Some(sv) = state.on_hub_step2() { + break sv; + } + } + RoomBinaryFrame::Doc { + doc_id: d, + message: DocMessage::Step1(sv), + } if d == doc_id => { + if let Some(sv) = state.on_hub_step1(sv) { + break sv; + } + } + _ => { + apply_incoming_frame(ws_session, awareness, ws, &b).await; + } + } + } + }; + + let diff_to_hub = ws_session.encode_diff_v1(doc_id, &hub_sv).unwrap(); + let rev_step2 = state.build_reverse_step2(diff_to_hub); + ws.send(WsMsg::Binary( + encode_binary_frame(&rev_step2).unwrap().into(), + )) + .await + .unwrap(); + + loop { + match ws.next().await.unwrap().unwrap() { + WsMsg::Text(t) => { + if let Ok(RoomControlFrame::Ready { doc_id: d }) = decode_control_frame(&t) + && d == doc_id + { + break; + } + } + WsMsg::Binary(b) => { + apply_incoming_frame(ws_session, awareness, ws, &b).await; + } + _ => {} + } + } +} + +#[tokio::main] +async fn main() { + let args = Args::parse(); + let mut ws_session = WorkspaceSession::new(&args.room, args.client_id).unwrap(); + let mut awareness = RoomAwareness::new(args.client_id).unwrap(); + let mut ws = connect_room(&args.relay_http, &args.room).await; + let http = reqwest::Client::new(); + + let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel::(); + std::thread::spawn(move || { + let stdin = io::stdin(); + for line in stdin.lock().lines().map_while(Result::ok) { + if cmd_tx.send(line).is_err() { + break; + } + } + }); + + println!("READY"); + let _ = io::stdout().flush(); + + while let Some(line) = cmd_rx.recv().await { + let trimmed = line.trim(); + if trimmed.is_empty() { + continue; + } + let cmd: Command = serde_json::from_str(trimmed).expect("valid JSON command"); + let reply: JsonValue = match cmd { + Command::SeedFullSchema { page_id, title } => { + ws_session.initialize_meta().unwrap(); + ws_session + .create_page(&page_id, &title, 1_700_000_000_000) + .unwrap(); + let page = ws_session.page_mut(&page_id).unwrap(); + page.add_block("page-1", BlockSpec::Page { title }, None, None, 10) + .unwrap(); + page.add_block("surface-1", BlockSpec::Surface, Some("page-1"), None, 20) + .unwrap(); + page.add_block( + "note-1", + BlockSpec::Note { + xywh: Some("[0,100,800,640]".to_string()), + }, + Some("page-1"), + None, + 30, + ) + .unwrap(); + page.add_block( + "p-1", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::H1, + text: "Native Title".to_string(), + }, + Some("note-1"), + None, + 40, + ) + .unwrap(); + page.add_block( + "p-2", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: "Shared paragraph text".to_string(), + }, + Some("note-1"), + None, + 45, + ) + .unwrap(); + page.add_block( + "l-1", + BlockSpec::List { + list_type: ListType::Todo, + text: "Item 1".to_string(), + checked: false, + order: None, + }, + Some("note-1"), + None, + 50, + ) + .unwrap(); + page.add_block("d-1", BlockSpec::Divider, Some("note-1"), None, 60) + .unwrap(); + page.add_block( + "c-1", + BlockSpec::Code { + text: "let x = 1;".to_string(), + language: Some("rust".to_string()), + caption: "".to_string(), + }, + Some("note-1"), + None, + 70, + ) + .unwrap(); + page.add_block( + "img-1", + BlockSpec::Image { + source_id: "blob-seed".to_string(), + caption: "".to_string(), + width: 100.0, + height: 100.0, + xywh: Some("[0,0,100,100]".to_string()), + }, + Some("note-1"), + None, + 80, + ) + .unwrap(); + page.add_block( + "bm-1", + BlockSpec::Bookmark { + url: "https://affine.pro".to_string(), + title: Some("AFFiNE".to_string()), + description: None, + }, + Some("note-1"), + None, + 90, + ) + .unwrap(); + page.add_block( + "frame-1", + BlockSpec::Frame { + title: "Frame 1".to_string(), + xywh: Some("[0,0,300,200]".to_string()), + presentation_index: Some("a0".to_string()), + }, + Some("surface-1"), + None, + 100, + ) + .unwrap(); + page.add_block( + "et-1", + BlockSpec::EdgelessText { + xywh: Some("[20,20,160,32]".to_string()), + }, + Some("surface-1"), + None, + 110, + ) + .unwrap(); + + // All 6 surface elements + page.add_surface_element( + "surface-1", + "el-shape", + "a0", + SurfaceElementSpec::Shape { + shape_type: "rect".to_string(), + xywh: "[10,10,120,80]".to_string(), + seed: 101, + filled: true, + text: Some("Shape".to_string()), + }, + 120, + ) + .unwrap(); + page.add_surface_element( + "surface-1", + "el-conn", + "a1", + SurfaceElementSpec::Connector { + mode: 2, + seed: 102, + source: ConnectorEndpointSpec::point(10.0, 10.0), + target: ConnectorEndpointSpec::point(200.0, 100.0), + text: None, + label_xywh: None, + }, + 130, + ) + .unwrap(); + page.add_surface_element( + "surface-1", + "el-brush", + "a2", + SurfaceElementSpec::Brush { + seed: 103, + points: vec![vec![0.0, 0.0], vec![10.0, 10.0]], + xywh: "[0,0,14,14]".to_string(), + }, + 140, + ) + .unwrap(); + page.add_surface_element( + "surface-1", + "el-hl", + "a3", + SurfaceElementSpec::Highlighter { + seed: 104, + points: vec![vec![0.0, 0.0], vec![15.0, 5.0]], + xywh: "[0,0,37,27]".to_string(), + }, + 150, + ) + .unwrap(); + page.add_surface_element( + "surface-1", + "el-text", + "a4", + SurfaceElementSpec::Text { + seed: 105, + text: "Note".to_string(), + xywh: "[40,40,80,24]".to_string(), + }, + 160, + ) + .unwrap(); + page.add_surface_element( + "surface-1", + "el-group", + "a5", + SurfaceElementSpec::Group { + seed: 106, + title: "Group".to_string(), + children: vec!["el-shape".to_string()], + }, + 170, + ) + .unwrap(); + + let room = ws_session.room().to_string(); + sync_single_doc(&mut ws, &mut ws_session, &mut awareness, &room).await; + sync_single_doc(&mut ws, &mut ws_session, &mut awareness, &page_id).await; + json!({ "ok": true }) + } + Command::SyncAll => { + let room = ws_session.room().to_string(); + sync_single_doc(&mut ws, &mut ws_session, &mut awareness, &room).await; + let pages = ws_session.list_pages().unwrap(); + for p in pages { + ws_session.ensure_page(&p.id).unwrap(); + sync_single_doc(&mut ws, &mut ws_session, &mut awareness, &p.id).await; + } + json!({ "ok": true }) + } + Command::Reconnect => { + let _ = ws.close(None).await; + ws = connect_room(&args.relay_http, &args.room).await; + let room = ws_session.room().to_string(); + sync_single_doc(&mut ws, &mut ws_session, &mut awareness, &room).await; + let pages = ws_session.list_pages().unwrap(); + for p in pages { + ws_session.ensure_page(&p.id).unwrap(); + sync_single_doc(&mut ws, &mut ws_session, &mut awareness, &p.id).await; + } + json!({ "ok": true }) + } + Command::InsertText { + page_id, + block_id, + index, + text, + now_ms, + } => { + let page = ws_session.ensure_page(&page_id).unwrap(); + let target = y_octo::TypeTarget::Path( + y_octo::TypePath::root("blocks") + .key(&block_id) + .key("prop:text"), + ); + let len = page.inner().read_text_len(&target).unwrap_or(0); + let clamped = index.min(len); + if let Some(c) = page + .insert_text(&block_id, "prop:text", clamped, &text, now_ms) + .unwrap() + && !c.update.is_empty() + { + let f = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id: page_id, + message: DocMessage::Update(c.update), + }) + .unwrap(); + ws.send(WsMsg::Binary(f.into())).await.unwrap(); + } + json!({ "ok": true }) + } + Command::RemoveText { + page_id, + block_id, + index, + len, + now_ms, + } => { + let page = ws_session.ensure_page(&page_id).unwrap(); + let target = y_octo::TypeTarget::Path( + y_octo::TypePath::root("blocks") + .key(&block_id) + .key("prop:text"), + ); + let cur_len = page.inner().read_text_len(&target).unwrap_or(0); + if cur_len > 0 && len > 0 { + let start = index.min(cur_len - 1); + let del = len.min(cur_len - start); + if let Some(c) = page + .remove_text(&block_id, "prop:text", start, del, now_ms) + .unwrap() + && !c.update.is_empty() + { + let f = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id: page_id, + message: DocMessage::Update(c.update), + }) + .unwrap(); + ws.send(WsMsg::Binary(f.into())).await.unwrap(); + } + } + json!({ "ok": true }) + } + Command::FormatText { + page_id, + block_id, + index, + len, + bold, + now_ms, + } => { + let page = ws_session.ensure_page(&page_id).unwrap(); + let target = y_octo::TypeTarget::Path( + y_octo::TypePath::root("blocks") + .key(&block_id) + .key("prop:text"), + ); + let cur_len = page.inner().read_text_len(&target).unwrap_or(0); + if cur_len > 0 && len > 0 { + let start = index.min(cur_len - 1); + let fmt_len = len.min(cur_len - start); + let mut attrs = TextAttributes::new(); + attrs.insert("bold".to_string(), if bold { Any::True } else { Any::Null }); + if let Some(c) = page + .format_text(&block_id, "prop:text", start, fmt_len, attrs, now_ms) + .unwrap() + && !c.update.is_empty() + { + let f = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id: page_id, + message: DocMessage::Update(c.update), + }) + .unwrap(); + ws.send(WsMsg::Binary(f.into())).await.unwrap(); + } + } + json!({ "ok": true }) + } + Command::ReorderChild { + page_id, + parent_id, + child_id, + new_index, + now_ms, + } => { + let page = ws_session.ensure_page(&page_id).unwrap(); + if let Ok(Some(c)) = page.reorder_child(&parent_id, &child_id, new_index, now_ms) + && !c.update.is_empty() + { + let f = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id: page_id, + message: DocMessage::Update(c.update), + }) + .unwrap(); + ws.send(WsMsg::Binary(f.into())).await.unwrap(); + } + json!({ "ok": true }) + } + Command::UpdateShapeXywh { + page_id, + surface_id, + element_id, + xywh, + now_ms, + } => { + let page = ws_session.ensure_page(&page_id).unwrap(); + if let Some(c) = page + .set_surface_element_field( + &surface_id, + &element_id, + "xywh", + SessionValue::Any(Any::String(xywh)), + now_ms, + ) + .unwrap() + && !c.update.is_empty() + { + let f = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id: page_id, + message: DocMessage::Update(c.update), + }) + .unwrap(); + ws.send(WsMsg::Binary(f.into())).await.unwrap(); + } + json!({ "ok": true }) + } + Command::UpdateConnectorMode { + page_id, + surface_id, + element_id, + mode, + now_ms, + } => { + let page = ws_session.ensure_page(&page_id).unwrap(); + if let Some(c) = page + .set_surface_element_field( + &surface_id, + &element_id, + "mode", + SessionValue::Any(Any::Integer(mode)), + now_ms, + ) + .unwrap() + && !c.update.is_empty() + { + let f = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id: page_id, + message: DocMessage::Update(c.update), + }) + .unwrap(); + ws.send(WsMsg::Binary(f.into())).await.unwrap(); + } + json!({ "ok": true }) + } + Command::SetAwareness { + name, + color, + store_key, + block_id, + index, + length, + now_ms, + } => { + let mut payload = AwarenessPayload::new(name, color); + payload + .set_text_selection( + store_key, + TextSelectionState::range( + TextRangePoint { + block_id, + index, + length, + }, + None, + false, + ), + ) + .unwrap(); + let bytes = awareness.set_local_payload(&payload, now_ms).unwrap(); + let frame = encode_binary_frame(&RoomBinaryFrame::Awareness(bytes)).unwrap(); + ws.send(WsMsg::Binary(frame.into())).await.unwrap(); + json!({ "ok": true }) + } + Command::TickAwareness { now_ms } => { + let tick = awareness.tick(now_ms).unwrap(); + if let Some(out) = tick.outbound_update { + let frame = encode_binary_frame(&RoomBinaryFrame::Awareness(out)).unwrap(); + ws.send(WsMsg::Binary(frame.into())).await.unwrap(); + } + json!({ + "ok": true, + "expired": tick.expired_clients, + "renewed": tick.renewed_local, + "activeRemotes": awareness.active_remote_clients(), + "expireTimeoutMs": AWARENESS_EXPIRE_TIMEOUT_MS, + }) + } + Command::UploadBlob { key, bytes } => { + let url = format!( + "{}/api/collection/{}/blob/{key}", + args.relay_http, args.room + ); + let resp = http.put(&url).body(bytes).send().await.unwrap(); + json!({ "ok": resp.status().is_success(), "status": resp.status().as_u16() }) + } + Command::FetchBlob { key } => { + let url = format!( + "{}/api/collection/{}/blob/{key}", + args.relay_http, args.room + ); + let resp = http.get(&url).send().await.unwrap(); + let ok = resp.status().is_success(); + let bytes = if ok { + resp.bytes().await.unwrap().to_vec() + } else { + Vec::new() + }; + json!({ "ok": ok, "bytes": bytes }) + } + Command::Drain { wait_ms } => { + let mut remaining_ms = wait_ms; + let step_ms = 25u64; + while remaining_ms > 0 { + let slice = remaining_ms.min(step_ms); + match tokio::time::timeout(std::time::Duration::from_millis(slice), ws.next()) + .await + { + Ok(Some(Ok(WsMsg::Binary(b)))) => { + apply_incoming_frame(&mut ws_session, &mut awareness, &mut ws, &b) + .await; + } + Ok(Some(Ok(_))) => {} + Ok(_) => break, + Err(_) => { + remaining_ms = remaining_ms.saturating_sub(slice); + } + } + } + json!({ + "ok": true, + "activeRemotes": awareness.active_remote_clients(), + }) + } + Command::ExportState { page_id } => { + let page = ws_session.ensure_page(&page_id).unwrap(); + let sv_bytes = page.encode_state_vector_v1().unwrap(); + let sv = StateVector::decode_v1(&sv_bytes).unwrap(); + let full_update_bytes = page.encode_update_v1().unwrap(); + let sv_map: std::collections::BTreeMap = sv + .iter() + .map(|(cid, clk)| (cid.to_string(), *clk)) + .collect(); + let doc_json = page.export_doc_json().unwrap(); + let remote_awareness: std::collections::BTreeMap = awareness + .active_remote_clients() + .into_iter() + .filter_map(|cid| { + awareness + .get_payload(cid) + .map(|p| (cid.to_string(), serde_json::to_value(p).unwrap())) + }) + .collect(); + + json!({ + "ok": true, + "stateVector": sv_map, + "fullUpdateV1": full_update_bytes, + "docJson": doc_json, + "remoteAwareness": remote_awareness, + }) + } + Command::Quit => { + let _ = ws.close(None).await; + println!("{}", json!({ "ok": true })); + let _ = io::stdout().flush(); + break; + } + }; + + println!("{reply}"); + let _ = io::stdout().flush(); + } +} diff --git a/blocksuite/native-playground/crates/doc/src/awareness.rs b/blocksuite/native-playground/crates/doc/src/awareness.rs new file mode 100644 index 0000000000..9e096cca91 --- /dev/null +++ b/blocksuite/native-playground/crates/doc/src/awareness.rs @@ -0,0 +1,271 @@ +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; +use y_octo::{Awareness, AwarenessEvent, AwarenessState, AwarenessStates}; + +use crate::{DocError, DocResult, validate_client_id}; + +/// Local awareness renewal interval matching `y-protocols/awareness.js` (15 seconds). +pub const AWARENESS_RENEW_INTERVAL_MS: u64 = 15_000; + +/// Remote awareness expiry timeout matching `y-protocols/awareness.js` (30 seconds). +pub const AWARENESS_EXPIRE_TIMEOUT_MS: u64 = 30_000; + +/// User descriptor inside BlockSuite's awareness JSON payload. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct AwarenessUser { + pub name: String, +} + +/// Endpoint of a BlockSuite `TextSelection` range (`framework/std/src/selection/text.ts`). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TextRangePoint { + pub block_id: String, + pub index: u64, + pub length: u64, +} + +/// BlockSuite `TextSelection` JSON representation matching `TextSelectionSchema`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TextSelectionState { + #[serde(rename = "type")] + pub kind: String, + pub from: TextRangePoint, + pub to: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub reverse: Option, +} + +impl TextSelectionState { + pub fn caret(block_id: impl Into, index: u64) -> Self { + Self { + kind: "text".to_string(), + from: TextRangePoint { + block_id: block_id.into(), + index, + length: 0, + }, + to: None, + reverse: None, + } + } + + pub fn range(from: TextRangePoint, to: Option, reverse: bool) -> Self { + Self { + kind: "text".to_string(), + from, + to, + reverse: Some(reverse), + } + } +} + +/// BlockSuite awareness payload matching `RawAwarenessState` in `@blocksuite/store`. +/// +/// Top-level `color` is mandatory so `doc-remote-selection.ts` renders remote selections. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AwarenessPayload { + pub user: AwarenessUser, + pub color: String, + #[serde(rename = "selectionV2", default)] + pub selection_v2: BTreeMap>, +} + +impl AwarenessPayload { + pub fn new(name: impl Into, color: impl Into) -> Self { + Self { + user: AwarenessUser { name: name.into() }, + color: color.into(), + selection_v2: BTreeMap::new(), + } + } + + pub fn set_selection( + &mut self, + store_key: impl Into, + selections: Vec, + ) { + self.selection_v2.insert(store_key.into(), selections); + } + + pub fn set_text_selection( + &mut self, + store_key: impl Into, + selection: TextSelectionState, + ) -> DocResult { + self.selection_v2 + .insert(store_key.into(), vec![serde_json::to_value(selection)?]); + Ok(()) + } + + pub fn validate(&self) -> DocResult { + if self.color.trim().is_empty() { + return Err(DocError::Awareness( + "top-level awareness color must be non-empty".to_string(), + )); + } + Ok(()) + } +} + +/// Output of a deterministic [`RoomAwareness::tick`] call. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct AwarenessTick { + /// Binary `y-protocols/awareness` update to broadcast if local state renewed or remotes expired. + pub outbound_update: Option>, + /// Remote client IDs expired during this tick. + pub expired_clients: Vec, + /// Whether the local client's state was renewed during this tick. + pub renewed_local: bool, +} + +/// Deterministic-clock wrapper around `y_octo::Awareness` for BlockSuite room presence. +pub struct RoomAwareness { + inner: Awareness, + last_local_broadcast_ms: Option, + remote_last_seen_ms: BTreeMap, +} + +impl RoomAwareness { + pub fn new(local_client_id: u64) -> DocResult { + let local_client_id = validate_client_id(local_client_id)?; + Ok(Self { + inner: Awareness::new(local_client_id), + last_local_broadcast_ms: None, + remote_last_seen_ms: BTreeMap::new(), + }) + } + + pub fn local_client_id(&self) -> u64 { + self.inner.local_id() + } + + pub fn states(&self) -> &AwarenessStates { + self.inner.get_states() + } + + /// Set the local BlockSuite awareness payload at `now_ms`, returning encoded binary bytes. + pub fn set_local_payload( + &mut self, + payload: &AwarenessPayload, + now_ms: u64, + ) -> DocResult> { + payload.validate()?; + let json = serde_json::to_string(payload)?; + self.inner.set_local_state(json); + self.last_local_broadcast_ms = Some(now_ms); + Ok(self.inner.encode_update(Some(&[self.inner.local_id()]))?) + } + + /// Mark the local client offline (`null`) and return the encoded removal update. + pub fn clear_local_state(&mut self) -> DocResult> { + self.inner.clear_local_state(); + self.last_local_broadcast_ms = None; + Ok(self.inner.encode_update(Some(&[self.inner.local_id()]))?) + } + + /// Decode and apply a `y-protocols/awareness` binary update at `now_ms`. + pub fn apply_update(&mut self, bytes: &[u8], now_ms: u64) -> DocResult { + let event = self.inner.apply_update_v1(bytes)?; + let local_id = self.inner.local_id(); + for &cid in event.added().iter().chain(event.updated().iter()) { + if cid != local_id { + self.remote_last_seen_ms.insert(cid, now_ms); + } + } + for &cid in event.removed() { + self.remote_last_seen_ms.remove(&cid); + } + Ok(event) + } + + /// Encode all known states (or a specific subset) as `y-protocols/awareness` binary bytes. + pub fn encode_update(&self, clients: Option<&[u64]>) -> DocResult> { + Ok(self.inner.encode_update(clients)?) + } + + /// Parse a client's active BlockSuite payload if present and not deleted (`"null"`). + pub fn get_payload(&self, client_id: u64) -> Option { + let state = self.inner.get_states().get(&client_id)?; + if state.is_deleted() { + return None; + } + serde_json::from_str::(state.content()).ok() + } + + /// List all currently active (non-deleted) remote client IDs. + pub fn active_remote_clients(&self) -> Vec { + let local_id = self.inner.local_id(); + let mut ids: Vec = self + .inner + .get_states() + .iter() + .filter(|&(&cid, st)| cid != local_id && !st.is_deleted()) + .map(|(&cid, _)| cid) + .collect(); + ids.sort_unstable(); + ids + } + + /// Advance the deterministic awareness clock to `now_ms`: + /// - Renews local presence if active and >= 15s since last broadcast. + /// - Expires remote peers unseen for >= 30s. + pub fn tick(&mut self, now_ms: u64) -> DocResult { + let mut changed_clients = Vec::new(); + let mut renewed_local = false; + + let local_id = self.inner.local_id(); + if let Some(last_ms) = self.last_local_broadcast_ms + && now_ms.saturating_sub(last_ms) >= AWARENESS_RENEW_INTERVAL_MS + && let Some(local_content) = self.inner.get_local_state() + && local_content != "null" + { + self.inner.set_local_state(local_content); + self.last_local_broadcast_ms = Some(now_ms); + changed_clients.push(local_id); + renewed_local = true; + } + + let expired_clients: Vec = self + .remote_last_seen_ms + .iter() + .filter_map(|(&cid, &seen_ms)| { + if now_ms.saturating_sub(seen_ms) >= AWARENESS_EXPIRE_TIMEOUT_MS { + Some(cid) + } else { + None + } + }) + .collect(); + + if !expired_clients.is_empty() { + let mut removals = AwarenessStates::new(); + for &cid in &expired_clients { + self.remote_last_seen_ms.remove(&cid); + let next_clock = self + .inner + .get_states() + .get(&cid) + .map_or(1, |s| s.clock().saturating_add(1)); + removals.insert(cid, AwarenessState::new(next_clock, "null".to_string())); + changed_clients.push(cid); + } + self.inner.apply_update(removals); + } + + let outbound_update = if changed_clients.is_empty() { + None + } else { + Some(self.inner.encode_update(Some(&changed_clients))?) + }; + + Ok(AwarenessTick { + outbound_update, + expired_clients, + renewed_local, + }) + } +} diff --git a/blocksuite/native-playground/crates/doc/src/bin/bs_relay.rs b/blocksuite/native-playground/crates/doc/src/bin/bs_relay.rs new file mode 100644 index 0000000000..73fb6b5a21 --- /dev/null +++ b/blocksuite/native-playground/crates/doc/src/bin/bs_relay.rs @@ -0,0 +1,39 @@ +#![forbid(unsafe_code)] + +use std::net::SocketAddr; + +use blocksuite_playground_doc::room::RoomHub; +use clap::Parser; +use tokio::net::TcpListener; + +#[derive(Debug, Parser)] +#[command(name = "bs-relay", about = "BlockSuite Playground binary room relay")] +struct Args { + #[arg(long, default_value = "127.0.0.1")] + host: String, + #[arg(long, default_value_t = 8788)] + port: u16, +} + +#[tokio::main] +async fn main() -> Result<(), Box> { + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()), + ) + .init(); + + let args = Args::parse(); + let bind_addr: SocketAddr = format!("{}:{}", args.host, args.port).parse()?; + let listener = TcpListener::bind(bind_addr).await?; + let local_addr = listener.local_addr()?; + println!("LISTENING {local_addr}"); + + let app = RoomHub::new().router(); + axum::serve(listener, app) + .with_graceful_shutdown(async { + let _ = tokio::signal::ctrl_c().await; + }) + .await?; + Ok(()) +} diff --git a/blocksuite/native-playground/crates/doc/src/lib.rs b/blocksuite/native-playground/crates/doc/src/lib.rs new file mode 100644 index 0000000000..7ccf93cbef --- /dev/null +++ b/blocksuite/native-playground/crates/doc/src/lib.rs @@ -0,0 +1,65 @@ +#![forbid(unsafe_code)] + +pub mod awareness; +#[cfg(all(feature = "server", not(target_family = "wasm")))] +pub mod room; +pub mod schema; +pub mod session; +pub mod wire; + +use thiserror::Error; + +/// Maximum client ID representable exactly as a JavaScript IEEE-754 integer (`2^53 - 1`). +pub const MAX_JS_CLIENT_ID: u64 = 0x001F_FFFF_FFFF_FFFF; + +/// Validate that a `client_id` is in the JavaScript-safe 53-bit range `1..=2^53-1`. +pub fn validate_client_id(client_id: u64) -> Result { + if client_id == 0 || client_id > MAX_JS_CLIENT_ID { + return Err(DocError::InvalidClientId(client_id)); + } + Ok(client_id) +} + +/// Deterministically derive a non-zero 53-bit client ID from an arbitrary seed. +/// +/// Safe on both native and `wasm32-unknown-unknown` targets without relying on +/// platform randomness or wall-clock time. +pub fn client_id_from_seed(seed: u64) -> u64 { + let mut z = seed.wrapping_add(0x9E37_79B9_7F4A_7C15); + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^= z >> 31; + let masked = z & MAX_JS_CLIENT_ID; + if masked == 0 { 1 } else { masked } +} + +/// Generate a random non-zero 53-bit client ID on native platforms. +#[cfg(not(target_family = "wasm"))] +pub fn random_client_id() -> u64 { + use rand::Rng; + rand::rng().random_range(1..=MAX_JS_CLIENT_ID) +} + +#[derive(Debug, Error)] +pub enum DocError { + #[error("invalid 53-bit client id: {0} (must be in 1..=2^53-1)")] + InvalidClientId(u64), + #[error("crdt codec error: {0}")] + Codec(#[from] y_octo::JwstCodecError), + #[error("wire protocol error: {0}")] + Wire(String), + #[error("awareness error: {0}")] + Awareness(String), + #[error("block not found: {0}")] + BlockNotFound(String), + #[error("surface element not found: {0}")] + ElementNotFound(String), + #[error("page not found: {0}")] + PageNotFound(String), + #[error("invalid document state: {0}")] + InvalidState(String), + #[error("serialization error: {0}")] + Json(#[from] serde_json::Error), +} + +pub type DocResult = Result; diff --git a/blocksuite/native-playground/crates/doc/src/room.rs b/blocksuite/native-playground/crates/doc/src/room.rs new file mode 100644 index 0000000000..1a447b494b --- /dev/null +++ b/blocksuite/native-playground/crates/doc/src/room.rs @@ -0,0 +1,688 @@ +use std::{ + collections::{HashMap, HashSet, VecDeque}, + sync::{ + Arc, + atomic::{AtomicU64, Ordering}, + }, +}; + +use axum::{ + Json, Router, + body::Bytes, + extract::{ + DefaultBodyLimit, Path, State, WebSocketUpgrade, + ws::{Message, WebSocket}, + }, + http::{HeaderMap, HeaderValue, StatusCode, header}, + response::{IntoResponse, Response}, + routing::get, +}; +use futures_util::{SinkExt, StreamExt}; +use serde_json::json; +use tokio::sync::{Mutex, mpsc}; +use y_octo::{ + Any, Awareness, AwarenessState, AwarenessStates, DocMessage, DocOptions, DocSession, + SessionConfig, SessionOriginKind, SessionReadValue, SessionUndoConfig, StateVector, TypePath, + TypeTarget, encode_state_vector_from_update_v1, +}; + +/// Maximum HTTP body size for `/api/collection/{id}/blob/{key}` (64 MiB). +const MAX_BLOB_BODY_BYTES: usize = 64 * 1024 * 1024; + +use crate::wire::{ + RoomBinaryFrame, RoomControlFrame, decode_binary_frame, decode_control_frame, + encode_binary_frame, encode_control_frame, +}; + +type ConnId = u64; +type OutboundTx = mpsc::UnboundedSender; + +enum SeedClaimState { + Pending { + winner_conn_id: ConnId, + waiters: VecDeque, + }, + Completed, +} + +fn doc_id_from_seed_key(key: &str) -> Option<&str> { + key.strip_prefix("seed:") +} + +struct RoomState { + docs: HashMap>, + /// `doc_id -> set of subscribed connection IDs` + subscriptions: HashMap>, + /// Active connections in this room. + conns: HashMap, + /// Single-winner CAS claims for initial seeding (`key -> Pending | Completed`). + seed_claims: HashMap, + /// Authoritative awareness state for this room (using hub sentinel ID 0). + awareness: Awareness, + /// Multi-connection awareness refcounting: `client_id -> set of conn_ids`. + awareness_refs: HashMap>, + /// Reverse index: `conn_id -> set of client_ids` announced on that connection. + conn_clients: HashMap>, + /// Randomized 53-bit hub client ID for internal `DocSession`s (rotated on collision). + hub_client_id: u64, +} + +impl RoomState { + fn new() -> Self { + Self { + docs: HashMap::new(), + subscriptions: HashMap::new(), + conns: HashMap::new(), + seed_claims: HashMap::new(), + awareness: Awareness::new(0), + awareness_refs: HashMap::new(), + conn_clients: HashMap::new(), + hub_client_id: crate::random_client_id(), + } + } + + fn doc_has_page_root(&self, doc_id: &str) -> bool { + let Some(doc) = self.docs.get(doc_id) else { + return false; + }; + let Ok(blocks) = doc.read_map(&TypeTarget::Path(TypePath::root("blocks"))) else { + return false; + }; + for (block_id, value) in blocks { + if matches!(value, SessionReadValue::Map(_)) { + let block_target = TypeTarget::Path(TypePath::root("blocks").key(&block_id)); + if let Ok(Some(SessionReadValue::Any(Any::String(flavour)))) = + doc.get_map_value(&block_target, "sys:flavour") + && flavour == "affine:page" + { + return true; + } + } + } + false + } + + fn maybe_complete_seed_claim_for_doc(&mut self, doc_id: &str) { + let key = format!("seed:{doc_id}"); + if !matches!( + self.seed_claims.get(&key), + Some(SeedClaimState::Pending { .. }) + ) { + return; + } + if !self.doc_has_page_root(doc_id) { + return; + } + if let Some(SeedClaimState::Pending { waiters, .. }) = self + .seed_claims + .insert(key.clone(), SeedClaimState::Completed) + && let Ok(reply) = + encode_control_frame(&RoomControlFrame::SeedClaimResult { key, winner: false }) + { + for waiter_id in waiters { + self.send_to(waiter_id, Message::Text(reply.clone().into())); + } + } + } + + fn doc_mut(&mut self, doc_id: &str) -> &mut DocSession<()> { + let hub_client_id = self.hub_client_id; + self.docs.entry(doc_id.to_string()).or_insert_with(|| { + DocSession::with_config( + DocOptions::from_identity(hub_client_id, doc_id.to_string()), + SessionConfig { + undo: SessionUndoConfig::Disabled, + }, + ) + }) + } + + fn send_to(&self, conn_id: ConnId, msg: Message) { + if let Some(tx) = self.conns.get(&conn_id) { + let _ = tx.send(msg); + } + } + + fn broadcast_doc_update(&self, doc_id: &str, update: Vec, exclude: Option) { + if update.is_empty() || (update.len() == 2 && update[0] == 0 && update[1] == 0) { + return; + } + let Ok(bytes) = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id: doc_id.to_string(), + message: DocMessage::Update(update), + }) else { + return; + }; + if let Some(subs) = self.subscriptions.get(doc_id) { + for &cid in subs { + if Some(cid) == exclude { + continue; + } + self.send_to(cid, Message::Binary(bytes.clone().into())); + } + } + } + + fn broadcast_awareness(&self, payload: Vec, exclude: Option) { + let Ok(bytes) = encode_binary_frame(&RoomBinaryFrame::Awareness(payload)) else { + return; + }; + for (&cid, tx) in &self.conns { + if Some(cid) == exclude { + continue; + } + let _ = tx.send(Message::Binary(bytes.clone().into())); + } + } + + fn handle_doc_message(&mut self, conn_id: ConnId, doc_id: String, msg: DocMessage) { + match msg { + DocMessage::Step1(client_sv) => { + // Atomically subscribe connection and compute Step2 + reverse Step1. + self.subscriptions + .entry(doc_id.clone()) + .or_default() + .insert(conn_id); + + let doc = self.doc_mut(&doc_id); + let diff_to_client = doc + .encode_diff_v1(&client_sv) + .unwrap_or_else(|_| vec![0, 0]); + let hub_sv = doc.encode_state_vector_v1().unwrap_or_else(|_| vec![0]); + + if let Ok(step2_bytes) = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id: doc_id.clone(), + message: DocMessage::Step2(diff_to_client), + }) { + self.send_to(conn_id, Message::Binary(step2_bytes.into())); + } + if let Ok(step1_bytes) = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id, + message: DocMessage::Step1(hub_sv), + }) { + self.send_to(conn_id, Message::Binary(step1_bytes.into())); + } + } + DocMessage::Step2(diff) => { + self.subscriptions + .entry(doc_id.clone()) + .or_default() + .insert(conn_id); + self.apply_and_broadcast(conn_id, &doc_id, &diff); + if let Ok(ready_text) = encode_control_frame(&RoomControlFrame::Ready { doc_id }) { + self.send_to(conn_id, Message::Text(ready_text.into())); + } + } + DocMessage::Update(update) => { + self.subscriptions + .entry(doc_id.clone()) + .or_default() + .insert(conn_id); + self.apply_and_broadcast(conn_id, &doc_id, &update); + } + } + } + + fn apply_and_broadcast(&mut self, sender: ConnId, doc_id: &str, bytes: &[u8]) { + if bytes.is_empty() || (bytes.len() == 2 && bytes[0] == 0 && bytes[1] == 0) { + return; + } + let commits = { + let doc = self.doc_mut(doc_id); + if let Ok(incoming_sv_bytes) = encode_state_vector_from_update_v1(bytes) + && let Ok(incoming_sv) = StateVector::decode_v1(&incoming_sv_bytes) + && (doc.client_required() || incoming_sv.contains_key(&doc.client())) + { + let mut next_id = crate::random_client_id(); + while incoming_sv.contains_key(&next_id) || next_id == doc.client() { + next_id = crate::random_client_id(); + } + doc.set_client(next_id); + } + let result = match doc.apply_update_v1(bytes) { + Ok(commits) => commits, + Err(err) => { + tracing::warn!(%doc_id, %err, "ignoring invalid CRDT update"); + return; + } + }; + if doc.client_required() { + doc.set_client(crate::random_client_id()); + } + result + }; + for commit in commits { + if commit.update.is_empty() { + continue; + } + if commit.origin_kind == SessionOriginKind::FormattingCleanup { + // Cleanup commit generated by hub must reach all subscribers including sender. + self.broadcast_doc_update(doc_id, commit.update, None); + } else { + // Broadcast only the actual incremental CommitEvent bytes to other peers. + self.broadcast_doc_update(doc_id, commit.update, Some(sender)); + } + } + self.maybe_complete_seed_claim_for_doc(doc_id); + } + + fn handle_awareness(&mut self, conn_id: ConnId, payload: Vec) { + // Decode incoming frame against a clean probe so equal-clock announcements + // still record `(client_id, conn_id)` ownership and explicit `"null"` removals + // are checked against remaining owners BEFORE mutating shared `self.awareness`. + let mut probe = Awareness::new(0); + if probe.apply_update_v1(&payload).is_err() { + return; + } + + let mut to_apply = AwarenessStates::new(); + for (&cid, state) in probe.get_states() { + if cid == 0 { + continue; + } + if state.is_deleted() { + let is_last = match self.awareness_refs.get_mut(&cid) { + Some(conns) => { + conns.remove(&conn_id); + if conns.is_empty() { + self.awareness_refs.remove(&cid); + true + } else { + false + } + } + None => true, + }; + if let Some(clients) = self.conn_clients.get_mut(&conn_id) { + clients.remove(&cid); + } + if is_last { + to_apply.insert(cid, state.clone()); + } + } else { + self.awareness_refs.entry(cid).or_default().insert(conn_id); + self.conn_clients.entry(conn_id).or_default().insert(cid); + to_apply.insert(cid, state.clone()); + } + } + + if to_apply.is_empty() { + return; + } + + let forward_clients: Vec = to_apply + .iter() + .filter_map(|(&cid, incoming)| { + let is_newer = self + .awareness + .get_states() + .get(&cid) + .is_none_or(|existing| incoming.clock() > existing.clock()); + is_newer.then_some(cid) + }) + .collect(); + + self.awareness.apply_update(to_apply); + + if !forward_clients.is_empty() + && let Ok(encoded) = self.awareness.encode_update(Some(&forward_clients)) + { + self.broadcast_awareness(encoded, Some(conn_id)); + } + } + + fn handle_control(&mut self, conn_id: ConnId, text: &str) { + let Ok(frame) = decode_control_frame(text) else { + return; + }; + if let RoomControlFrame::SeedClaim { key } = frame { + let Some(doc_id) = doc_id_from_seed_key(&key) else { + // Generic non-doc CAS key: single-winner immediate decision. + let winner = !self.seed_claims.contains_key(&key); + if winner { + self.seed_claims + .insert(key.clone(), SeedClaimState::Completed); + } + if let Ok(reply) = + encode_control_frame(&RoomControlFrame::SeedClaimResult { key, winner }) + { + self.send_to(conn_id, Message::Text(reply.into())); + } + return; + }; + + if self.doc_has_page_root(doc_id) { + self.seed_claims + .insert(key.clone(), SeedClaimState::Completed); + if let Ok(reply) = + encode_control_frame(&RoomControlFrame::SeedClaimResult { key, winner: false }) + { + self.send_to(conn_id, Message::Text(reply.into())); + } + return; + } + + match self.seed_claims.get_mut(&key) { + None => { + self.seed_claims.insert( + key.clone(), + SeedClaimState::Pending { + winner_conn_id: conn_id, + waiters: VecDeque::new(), + }, + ); + if let Ok(reply) = encode_control_frame(&RoomControlFrame::SeedClaimResult { + key, + winner: true, + }) { + self.send_to(conn_id, Message::Text(reply.into())); + } + } + Some(SeedClaimState::Completed) => { + if let Ok(reply) = encode_control_frame(&RoomControlFrame::SeedClaimResult { + key, + winner: false, + }) { + self.send_to(conn_id, Message::Text(reply.into())); + } + } + Some(SeedClaimState::Pending { + winner_conn_id, + waiters, + }) => { + if *winner_conn_id == conn_id { + if let Ok(reply) = + encode_control_frame(&RoomControlFrame::SeedClaimResult { + key, + winner: true, + }) + { + self.send_to(conn_id, Message::Text(reply.into())); + } + } else if !waiters.contains(&conn_id) { + waiters.push_back(conn_id); + } + } + } + } + } + + fn on_connect(&mut self, conn_id: ConnId, tx: OutboundTx) { + self.conns.insert(conn_id, tx); + // Send currently active awareness states to the newly connected peer. + let active: Vec = self + .awareness + .get_states() + .iter() + .filter(|(_, s)| !s.is_deleted()) + .map(|(&cid, _)| cid) + .collect(); + if !active.is_empty() + && let Ok(encoded) = self.awareness.encode_update(Some(&active)) + && let Ok(frame) = encode_binary_frame(&RoomBinaryFrame::Awareness(encoded)) + { + self.send_to(conn_id, Message::Binary(frame.into())); + } + } + + fn on_disconnect(&mut self, conn_id: ConnId) { + self.conns.remove(&conn_id); + for subs in self.subscriptions.values_mut() { + subs.remove(&conn_id); + } + + // Recover any pending seed claim abandoned by a disconnecting winner. + let mut keys_to_remove = Vec::new(); + let mut notifications: Vec<(ConnId, String, bool)> = Vec::new(); + let completed_docs: HashSet = self + .seed_claims + .keys() + .filter_map(|k| { + doc_id_from_seed_key(k) + .filter(|doc_id| self.doc_has_page_root(doc_id)) + .map(|_| k.clone()) + }) + .collect(); + + for (key, state) in &mut self.seed_claims { + if let SeedClaimState::Pending { + winner_conn_id, + waiters, + } = state + { + waiters.retain(|&c| c != conn_id); + if *winner_conn_id == conn_id { + if completed_docs.contains(key) { + for waiter_id in waiters.drain(..) { + notifications.push((waiter_id, key.clone(), false)); + } + *state = SeedClaimState::Completed; + } else { + let mut promoted = None; + while let Some(next_id) = waiters.pop_front() { + if self.conns.contains_key(&next_id) { + promoted = Some(next_id); + break; + } + } + if let Some(next_id) = promoted { + *winner_conn_id = next_id; + notifications.push((next_id, key.clone(), true)); + } else { + keys_to_remove.push(key.clone()); + } + } + } + } + } + for key in keys_to_remove { + self.seed_claims.remove(&key); + } + for (target_conn, key, winner) in notifications { + if let Ok(reply) = + encode_control_frame(&RoomControlFrame::SeedClaimResult { key, winner }) + { + self.send_to(target_conn, Message::Text(reply.into())); + } + } + + let Some(clients) = self.conn_clients.remove(&conn_id) else { + return; + }; + let mut removals = AwarenessStates::new(); + let mut removed_ids = Vec::new(); + + for cid in clients { + let is_last = match self.awareness_refs.get_mut(&cid) { + Some(conns) => { + conns.remove(&conn_id); + if conns.is_empty() { + self.awareness_refs.remove(&cid); + true + } else { + false + } + } + None => true, + }; + if is_last { + let next_clock = self + .awareness + .get_states() + .get(&cid) + .map_or(1, |s| s.clock().saturating_add(1)); + removals.insert(cid, AwarenessState::new(next_clock, "null".to_string())); + removed_ids.push(cid); + } + } + + if !removed_ids.is_empty() { + self.awareness.apply_update(removals); + if let Ok(encoded) = self.awareness.encode_update(Some(&removed_ids)) { + self.broadcast_awareness(encoded, None); + } + } + } +} + +type BlobKey = (String, String); +type BlobEntry = (Bytes, Option); +type BlobMap = HashMap; + +/// Shared state for the single-port `bs_room` HTTP + WebSocket Hub. +#[derive(Clone, Default)] +pub struct RoomHub { + rooms: Arc>>>>, + blobs: Arc>, + next_conn_id: Arc, +} + +impl RoomHub { + pub fn new() -> Self { + Self::default() + } + + pub fn router(self) -> Router { + Router::new() + .route("/healthz", get(healthz)) + .route("/native-sync/rooms/{room}", get(ws_room_handler)) + .route( + "/api/collection/{id}/blob/{key}", + get(blob_get) + .put(blob_put) + .delete(blob_delete) + .options(blob_options), + ) + .layer(DefaultBodyLimit::max(MAX_BLOB_BODY_BYTES)) + .with_state(self) + } + + async fn get_or_create_room(&self, room: &str) -> Arc> { + let mut guard = self.rooms.lock().await; + guard + .entry(room.to_string()) + .or_insert_with(|| Arc::new(Mutex::new(RoomState::new()))) + .clone() + } +} + +async fn healthz() -> impl IntoResponse { + Json(json!({ "status": "ok" })) +} + +async fn ws_room_handler( + Path(room): Path, + State(hub): State, + ws: WebSocketUpgrade, +) -> impl IntoResponse { + ws.on_upgrade(move |socket| handle_socket(hub, room, socket)) +} + +async fn handle_socket(hub: RoomHub, room_name: String, socket: WebSocket) { + let conn_id = hub.next_conn_id.fetch_add(1, Ordering::Relaxed) + 1; + let room = hub.get_or_create_room(&room_name).await; + let (mut ws_sink, mut ws_stream) = socket.split(); + let (tx, mut rx) = mpsc::unbounded_channel::(); + + { + let mut guard = room.lock().await; + guard.on_connect(conn_id, tx); + } + + let writer = tokio::spawn(async move { + while let Some(msg) = rx.recv().await { + if ws_sink.send(msg).await.is_err() { + break; + } + } + }); + + while let Some(Ok(msg)) = ws_stream.next().await { + match msg { + Message::Binary(bytes) => match decode_binary_frame(&bytes) { + Ok(RoomBinaryFrame::Doc { doc_id, message }) => { + let mut guard = room.lock().await; + guard.handle_doc_message(conn_id, doc_id, message); + } + Ok(RoomBinaryFrame::Awareness(payload)) => { + let mut guard = room.lock().await; + guard.handle_awareness(conn_id, payload); + } + Err(err) => { + tracing::warn!(%room_name, %conn_id, %err, "malformed binary frame"); + } + }, + Message::Text(text) => { + let mut guard = room.lock().await; + guard.handle_control(conn_id, &text); + } + Message::Close(_) => break, + _ => {} + } + } + + { + let mut guard = room.lock().await; + guard.on_disconnect(conn_id); + } + writer.abort(); +} + +fn with_blob_cors(mut response: Response) -> Response { + let headers = response.headers_mut(); + headers.insert( + header::ACCESS_CONTROL_ALLOW_ORIGIN, + HeaderValue::from_static("*"), + ); + headers.insert( + header::ACCESS_CONTROL_ALLOW_METHODS, + HeaderValue::from_static("GET, PUT, DELETE, POST, OPTIONS"), + ); + headers.insert( + header::ACCESS_CONTROL_ALLOW_HEADERS, + HeaderValue::from_static("Content-Type"), + ); + response +} + +async fn blob_options() -> Response { + with_blob_cors(StatusCode::NO_CONTENT.into_response()) +} + +async fn blob_get(Path((id, key)): Path<(String, String)>, State(hub): State) -> Response { + let guard = hub.blobs.lock().await; + let resp = match guard.get(&(id, key)) { + Some((data, content_type)) => { + let ct = content_type + .clone() + .unwrap_or_else(|| "application/octet-stream".to_string()); + ([(header::CONTENT_TYPE, ct)], data.clone()).into_response() + } + None => StatusCode::NOT_FOUND.into_response(), + }; + with_blob_cors(resp) +} + +async fn blob_put( + Path((id, key)): Path<(String, String)>, + State(hub): State, + headers: HeaderMap, + body: Bytes, +) -> Response { + let content_type = headers + .get(header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .map(ToString::to_string); + let mut guard = hub.blobs.lock().await; + guard.insert((id, key), (body, content_type)); + with_blob_cors(StatusCode::OK.into_response()) +} + +async fn blob_delete( + Path((id, key)): Path<(String, String)>, + State(hub): State, +) -> Response { + let mut guard = hub.blobs.lock().await; + guard.remove(&(id, key)); + with_blob_cors(StatusCode::OK.into_response()) +} diff --git a/blocksuite/native-playground/crates/doc/src/schema.rs b/blocksuite/native-playground/crates/doc/src/schema.rs new file mode 100644 index 0000000000..c9d8cf487a --- /dev/null +++ b/blocksuite/native-playground/crates/doc/src/schema.rs @@ -0,0 +1,938 @@ +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; +use y_octo::{AHashMap, Any, SessionValue, TextDeltaOp, TextInsert}; + +/// BlockSuite internal marker for `Boxed` values inside a `Y.Map`. +pub const NATIVE_UNIQ_IDENTIFIER: &str = "$blocksuite:internal:native$"; + +/// Default Note dimensions (`450 + 24 * 2`, `92`). +pub const DEFAULT_NOTE_WIDTH: f64 = 498.0; +pub const DEFAULT_NOTE_HEIGHT: f64 = 92.0; + +/// Default roughness for surface shapes and connectors. +pub const DEFAULT_ROUGHNESS: f64 = 1.4; + +/// Default highlighter stroke width. +pub const DEFAULT_HIGHLIGHTER_LINE_WIDTH: f64 = 22.0; + +/// Default connector label max width. +pub const CONNECTOR_LABEL_MAX_WIDTH: f64 = 280.0; + +/// Exact schema versions for all built-in `AffineSchemas` blocks. +pub fn affine_block_versions() -> BTreeMap<&'static str, i32> { + BTreeMap::from([ + ("affine:attachment", 1), + ("affine:bookmark", 1), + ("affine:callout", 1), + ("affine:code", 1), + ("affine:data-view", 1), + ("affine:database", 3), + ("affine:divider", 1), + ("affine:edgeless-text", 1), + ("affine:embed-figma", 1), + ("affine:embed-github", 1), + ("affine:embed-html", 1), + ("affine:embed-linked-doc", 1), + ("affine:embed-loom", 1), + ("affine:embed-synced-doc", 1), + ("affine:embed-youtube", 1), + ("affine:frame", 1), + ("affine:image", 1), + ("affine:latex", 1), + ("affine:list", 1), + ("affine:note", 1), + ("affine:page", 2), + ("affine:paragraph", 1), + ("affine:surface", 5), + ("affine:surface-ref", 1), + ("affine:table", 1), + ]) +} + +/// Phase-1 block flavours authored natively with full default properties. +#[derive(Debug, Clone, PartialEq)] +pub enum BlockSpec { + Page { + title: String, + }, + Surface, + Note { + xywh: Option, + }, + Paragraph { + paragraph_type: ParagraphType, + text: String, + }, + List { + list_type: ListType, + text: String, + checked: bool, + order: Option, + }, + Divider, + Code { + text: String, + language: Option, + caption: String, + }, + Image { + source_id: String, + caption: String, + width: f64, + height: f64, + xywh: Option, + }, + Bookmark { + url: String, + title: Option, + description: Option, + }, + Frame { + title: String, + xywh: Option, + presentation_index: Option, + }, + EdgelessText { + xywh: Option, + }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ParagraphType { + Text, + H1, + H2, + H3, + H4, + H5, + H6, + Quote, +} + +impl ParagraphType { + pub fn as_str(self) -> &'static str { + match self { + Self::Text => "text", + Self::H1 => "h1", + Self::H2 => "h2", + Self::H3 => "h3", + Self::H4 => "h4", + Self::H5 => "h5", + Self::H6 => "h6", + Self::Quote => "quote", + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ListType { + Bulleted, + Numbered, + Todo, + Toggle, +} + +impl ListType { + pub fn as_str(self) -> &'static str { + match self { + Self::Bulleted => "bulleted", + Self::Numbered => "numbered", + Self::Todo => "todo", + Self::Toggle => "toggle", + } + } +} + +/// Read-only descriptor for unknown/complex blocks preserved losslessly during edits & sync. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct UnknownBlock { + pub id: String, + pub flavour: String, + pub version: Option, + pub children: Vec, + pub prop_keys: Vec, +} + +/// Phase-1 surface element specs written into `affine:surface` `prop:elements` (`Boxed(Y.Map)`). +#[derive(Debug, Clone, PartialEq)] +pub enum SurfaceElementSpec { + Shape { + shape_type: String, + xywh: String, + seed: i32, + filled: bool, + text: Option, + }, + Connector { + mode: i32, + seed: i32, + source: ConnectorEndpointSpec, + target: ConnectorEndpointSpec, + text: Option, + /// Only persisted when explicitly moved locally; `None` by default. + label_xywh: Option<[f64; 4]>, + }, + Brush { + seed: i32, + points: Vec>, + xywh: String, + }, + Highlighter { + seed: i32, + points: Vec>, + xywh: String, + }, + Text { + seed: i32, + text: String, + xywh: String, + }, + Group { + seed: i32, + title: String, + children: Vec, + }, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct ConnectorEndpointSpec { + pub id: Option, + pub position: Option<[f64; 2]>, +} + +impl ConnectorEndpointSpec { + pub fn point(x: f64, y: f64) -> Self { + Self { + id: None, + position: Some([x, y]), + } + } + + pub fn element(id: impl Into, position: Option<[f64; 2]>) -> Self { + Self { + id: Some(id.into()), + position, + } + } + + pub fn to_any(&self) -> Any { + let mut map = AHashMap::default(); + if let Some(id) = &self.id { + map.insert("id".to_string(), Any::String(id.clone())); + } + if let Some([x, y]) = self.position { + map.insert( + "position".to_string(), + Any::Array(vec![Any::Float64(x.into()), Any::Float64(y.into())]), + ); + } + Any::Object(Box::new(map)) + } +} + +fn text_value(s: &str) -> SessionValue { + if s.is_empty() { + SessionValue::Text(Vec::new()) + } else { + SessionValue::Text(vec![TextDeltaOp::Insert { + insert: TextInsert::Text(s.to_string()), + format: None, + }]) + } +} + +fn color_map(dark: &str, light: &str) -> SessionValue { + SessionValue::Map(vec![ + ( + "dark".to_string(), + SessionValue::Any(Any::String(dark.to_string())), + ), + ( + "light".to_string(), + SessionValue::Any(Any::String(light.to_string())), + ), + ]) +} + +fn color_any(dark: &str, light: &str) -> Any { + let mut map = AHashMap::default(); + map.insert("dark".to_string(), Any::String(dark.to_string())); + map.insert("light".to_string(), Any::String(light.to_string())); + Any::Object(Box::new(map)) +} + +fn nonzero_seed(seed: i32) -> i32 { + if seed == 0 { 1 } else { seed.saturating_abs() } +} + +/// Wrap a plain JSON array for insertion as a single `Y.Map` entry. +/// +/// `y-octo`'s `From for Content` converts a top-level `Any::Array(v)` into +/// multi-element `Content::Any(v)`. Wrapping once produces `Content::Any(vec![Any::Array(v)])`, +/// matching Yjs `yMap.set(key, array)`. +fn map_array_any(items: Vec) -> Any { + Any::Array(vec![Any::Array(items)]) +} + +impl BlockSpec { + pub fn flavour(&self) -> &'static str { + match self { + Self::Page { .. } => "affine:page", + Self::Surface => "affine:surface", + Self::Note { .. } => "affine:note", + Self::Paragraph { .. } => "affine:paragraph", + Self::List { .. } => "affine:list", + Self::Divider => "affine:divider", + Self::Code { .. } => "affine:code", + Self::Image { .. } => "affine:image", + Self::Bookmark { .. } => "affine:bookmark", + Self::Frame { .. } => "affine:frame", + Self::EdgelessText { .. } => "affine:edgeless-text", + } + } + + pub fn version(&self) -> i32 { + match self { + Self::Page { .. } => 2, + Self::Surface => 5, + _ => 1, + } + } + + /// Build the complete `Y.Map` entries (`sys:*` + all default `prop:*`) for this block. + pub fn into_yblock_entries(self, id: &str) -> Vec<(String, SessionValue)> { + let flavour = self.flavour(); + let version = self.version(); + let mut entries = vec![ + ( + "sys:id".to_string(), + SessionValue::Any(Any::String(id.to_string())), + ), + ( + "sys:flavour".to_string(), + SessionValue::Any(Any::String(flavour.to_string())), + ), + ( + "sys:version".to_string(), + SessionValue::Any(Any::Integer(version)), + ), + ("sys:children".to_string(), SessionValue::Array(Vec::new())), + ]; + + match self { + Self::Page { title } => { + entries.push(("prop:title".to_string(), text_value(&title))); + } + Self::Surface => { + entries.push(( + "prop:elements".to_string(), + SessionValue::Map(vec![ + ( + "type".to_string(), + SessionValue::Any(Any::String(NATIVE_UNIQ_IDENTIFIER.to_string())), + ), + ("value".to_string(), SessionValue::Map(Vec::new())), + ]), + )); + } + Self::Note { xywh } => { + let xywh = xywh + .unwrap_or_else(|| format!("[0,0,{DEFAULT_NOTE_WIDTH},{DEFAULT_NOTE_HEIGHT}]")); + entries.extend([ + ( + "prop:xywh".to_string(), + SessionValue::Any(Any::String(xywh)), + ), + ( + "prop:background".to_string(), + color_map("#252525", "#ffffff"), + ), + ( + "prop:index".to_string(), + SessionValue::Any(Any::String("a0".to_string())), + ), + ( + "prop:lockedBySelf".to_string(), + SessionValue::Any(Any::False), + ), + ("prop:hidden".to_string(), SessionValue::Any(Any::False)), + ( + "prop:displayMode".to_string(), + SessionValue::Any(Any::String("both".to_string())), + ), + ( + "prop:edgeless".to_string(), + SessionValue::Map(vec![( + "style".to_string(), + SessionValue::Map(vec![ + ( + "borderRadius".to_string(), + SessionValue::Any(Any::Integer(8)), + ), + ("borderSize".to_string(), SessionValue::Any(Any::Integer(4))), + ( + "borderStyle".to_string(), + SessionValue::Any(Any::String("none".to_string())), + ), + ( + "shadowType".to_string(), + SessionValue::Any(Any::String( + "--affine-note-shadow-box".to_string(), + )), + ), + ]), + )]), + ), + ]); + } + Self::Paragraph { + paragraph_type, + text, + } => { + entries.extend([ + ( + "prop:type".to_string(), + SessionValue::Any(Any::String(paragraph_type.as_str().to_string())), + ), + ("prop:text".to_string(), text_value(&text)), + ("prop:collapsed".to_string(), SessionValue::Any(Any::False)), + ]); + } + Self::List { + list_type, + text, + checked, + order, + } => { + entries.extend([ + ( + "prop:type".to_string(), + SessionValue::Any(Any::String(list_type.as_str().to_string())), + ), + ("prop:text".to_string(), text_value(&text)), + ( + "prop:checked".to_string(), + SessionValue::Any(if checked { Any::True } else { Any::False }), + ), + ("prop:collapsed".to_string(), SessionValue::Any(Any::False)), + ( + "prop:order".to_string(), + SessionValue::Any(order.map_or(Any::Null, Any::Integer)), + ), + ]); + } + Self::Divider => {} + Self::Code { + text, + language, + caption, + } => { + entries.extend([ + ("prop:text".to_string(), text_value(&text)), + ( + "prop:language".to_string(), + SessionValue::Any(language.map_or(Any::Null, Any::String)), + ), + ("prop:wrap".to_string(), SessionValue::Any(Any::False)), + ( + "prop:caption".to_string(), + SessionValue::Any(Any::String(caption)), + ), + ]); + } + Self::Image { + source_id, + caption, + width, + height, + xywh, + } => { + entries.extend([ + ( + "prop:caption".to_string(), + SessionValue::Any(Any::String(caption)), + ), + ( + "prop:sourceId".to_string(), + SessionValue::Any(Any::String(source_id)), + ), + ( + "prop:width".to_string(), + SessionValue::Any(Any::Float64(width.into())), + ), + ( + "prop:height".to_string(), + SessionValue::Any(Any::Float64(height.into())), + ), + ( + "prop:index".to_string(), + SessionValue::Any(Any::String("a0".to_string())), + ), + ( + "prop:xywh".to_string(), + SessionValue::Any(Any::String( + xywh.unwrap_or_else(|| "[0,0,0,0]".to_string()), + )), + ), + ( + "prop:lockedBySelf".to_string(), + SessionValue::Any(Any::False), + ), + ( + "prop:rotate".to_string(), + SessionValue::Any(Any::Integer(0)), + ), + ("prop:size".to_string(), SessionValue::Any(Any::Integer(-1))), + ]); + } + Self::Bookmark { + url, + title, + description, + } => { + entries.extend([ + ( + "prop:style".to_string(), + SessionValue::Any(Any::String("horizontal".to_string())), + ), + ("prop:url".to_string(), SessionValue::Any(Any::String(url))), + ("prop:caption".to_string(), SessionValue::Any(Any::Null)), + ( + "prop:description".to_string(), + SessionValue::Any(description.map_or(Any::Null, Any::String)), + ), + ("prop:icon".to_string(), SessionValue::Any(Any::Null)), + ("prop:image".to_string(), SessionValue::Any(Any::Null)), + ( + "prop:title".to_string(), + SessionValue::Any(title.map_or(Any::Null, Any::String)), + ), + ( + "prop:index".to_string(), + SessionValue::Any(Any::String("a0".to_string())), + ), + ( + "prop:xywh".to_string(), + SessionValue::Any(Any::String("[0,0,0,0]".to_string())), + ), + ( + "prop:lockedBySelf".to_string(), + SessionValue::Any(Any::False), + ), + ( + "prop:rotate".to_string(), + SessionValue::Any(Any::Integer(0)), + ), + ( + "prop:footnoteIdentifier".to_string(), + SessionValue::Any(Any::Null), + ), + ]); + } + Self::Frame { + title, + xywh, + presentation_index, + } => { + entries.extend([ + ("prop:title".to_string(), text_value(&title)), + ( + "prop:background".to_string(), + SessionValue::Any(Any::String("transparent".to_string())), + ), + ( + "prop:xywh".to_string(), + SessionValue::Any(Any::String( + xywh.unwrap_or_else(|| "[0,0,100,100]".to_string()), + )), + ), + ( + "prop:index".to_string(), + SessionValue::Any(Any::String("a0".to_string())), + ), + ( + "prop:childElementIds".to_string(), + SessionValue::Map(Vec::new()), + ), + ( + "prop:presentationIndex".to_string(), + SessionValue::Any(Any::String( + presentation_index.unwrap_or_else(|| "a0".to_string()), + )), + ), + ( + "prop:lockedBySelf".to_string(), + SessionValue::Any(Any::False), + ), + ]); + } + Self::EdgelessText { xywh } => { + entries.extend([ + ( + "prop:xywh".to_string(), + SessionValue::Any(Any::String( + xywh.unwrap_or_else(|| "[0,0,16,16]".to_string()), + )), + ), + ( + "prop:index".to_string(), + SessionValue::Any(Any::String("a0".to_string())), + ), + ( + "prop:lockedBySelf".to_string(), + SessionValue::Any(Any::False), + ), + ("prop:scale".to_string(), SessionValue::Any(Any::Integer(1))), + ( + "prop:rotate".to_string(), + SessionValue::Any(Any::Integer(0)), + ), + ( + "prop:hasMaxWidth".to_string(), + SessionValue::Any(Any::False), + ), + ("prop:color".to_string(), color_map("#ffffff", "#000000")), + ( + "prop:fontFamily".to_string(), + SessionValue::Any(Any::String("blocksuite:surface:Inter".to_string())), + ), + ( + "prop:fontStyle".to_string(), + SessionValue::Any(Any::String("normal".to_string())), + ), + ( + "prop:fontWeight".to_string(), + SessionValue::Any(Any::String("400".to_string())), + ), + ( + "prop:textAlign".to_string(), + SessionValue::Any(Any::String("left".to_string())), + ), + ]); + } + } + + entries + } +} + +impl SurfaceElementSpec { + pub fn element_type(&self) -> &'static str { + match self { + Self::Shape { .. } => "shape", + Self::Connector { .. } => "connector", + Self::Brush { .. } => "brush", + Self::Highlighter { .. } => "highlighter", + Self::Text { .. } => "text", + Self::Group { .. } => "group", + } + } + + /// Build the complete `Y.Map` entries for a surface element inside `prop:elements.value`. + pub fn into_ymap_entries(self, id: &str, index: &str) -> Vec<(String, SessionValue)> { + let el_type = self.element_type(); + let mut entries = vec![ + ( + "id".to_string(), + SessionValue::Any(Any::String(id.to_string())), + ), + ( + "type".to_string(), + SessionValue::Any(Any::String(el_type.to_string())), + ), + ( + "index".to_string(), + SessionValue::Any(Any::String(index.to_string())), + ), + ("hidden".to_string(), SessionValue::Any(Any::False)), + ("lockedBySelf".to_string(), SessionValue::Any(Any::False)), + ]; + + match self { + Self::Shape { + shape_type, + xywh, + seed, + filled, + text, + } => { + let yellow = color_any("#f5c211", "#f5c211"); + entries.extend([ + ( + "seed".to_string(), + SessionValue::Any(Any::Integer(nonzero_seed(seed))), + ), + ( + "color".to_string(), + SessionValue::Any(Any::String("#000000".to_string())), + ), + ("fillColor".to_string(), SessionValue::Any(yellow.clone())), + ( + "filled".to_string(), + SessionValue::Any(if filled { Any::True } else { Any::False }), + ), + ( + "fontFamily".to_string(), + SessionValue::Any(Any::String("blocksuite:surface:Inter".to_string())), + ), + ("fontSize".to_string(), SessionValue::Any(Any::Integer(20))), + ( + "fontStyle".to_string(), + SessionValue::Any(Any::String("normal".to_string())), + ), + ( + "fontWeight".to_string(), + SessionValue::Any(Any::String("400".to_string())), + ), + ("maxWidth".to_string(), SessionValue::Any(Any::False)), + ( + "padding".to_string(), + SessionValue::Any(map_array_any(vec![Any::Integer(10), Any::Integer(20)])), + ), + ("radius".to_string(), SessionValue::Any(Any::Integer(0))), + ("rotate".to_string(), SessionValue::Any(Any::Integer(0))), + ( + "roughness".to_string(), + SessionValue::Any(Any::Float64(DEFAULT_ROUGHNESS.into())), + ), + ("shadow".to_string(), SessionValue::Any(Any::Null)), + ( + "shapeStyle".to_string(), + SessionValue::Any(Any::String("General".to_string())), + ), + ( + "shapeType".to_string(), + SessionValue::Any(Any::String(shape_type)), + ), + ("strokeColor".to_string(), SessionValue::Any(yellow)), + ( + "strokeStyle".to_string(), + SessionValue::Any(Any::String("solid".to_string())), + ), + ( + "strokeWidth".to_string(), + SessionValue::Any(Any::Integer(4)), + ), + ( + "textAlign".to_string(), + SessionValue::Any(Any::String("center".to_string())), + ), + ( + "textHorizontalAlign".to_string(), + SessionValue::Any(Any::String("center".to_string())), + ), + ( + "textResizing".to_string(), + SessionValue::Any(Any::Integer(1)), + ), + ( + "textVerticalAlign".to_string(), + SessionValue::Any(Any::String("center".to_string())), + ), + ("xywh".to_string(), SessionValue::Any(Any::String(xywh))), + ]); + if let Some(text_str) = text { + entries.push(("text".to_string(), text_value(&text_str))); + } + } + Self::Connector { + mode, + seed, + source, + target, + text, + label_xywh, + } => { + let mut label_constraints = AHashMap::default(); + label_constraints.insert("hasMaxWidth".to_string(), Any::True); + label_constraints.insert( + "maxWidth".to_string(), + Any::Float64(CONNECTOR_LABEL_MAX_WIDTH.into()), + ); + + let mut label_offset = AHashMap::default(); + label_offset.insert("distance".to_string(), Any::Float64(0.5.into())); + label_offset.insert("anchor".to_string(), Any::String("center".to_string())); + + let mut label_style = AHashMap::default(); + label_style.insert("color".to_string(), color_any("#ffffff", "#000000")); + label_style.insert( + "fontFamily".to_string(), + Any::String("blocksuite:surface:Inter".to_string()), + ); + label_style.insert("fontSize".to_string(), Any::Integer(16)); + label_style.insert("fontStyle".to_string(), Any::String("normal".to_string())); + label_style.insert("fontWeight".to_string(), Any::String("400".to_string())); + label_style.insert("textAlign".to_string(), Any::String("center".to_string())); + + entries.extend([ + ( + "seed".to_string(), + SessionValue::Any(Any::Integer(nonzero_seed(seed))), + ), + ("mode".to_string(), SessionValue::Any(Any::Integer(mode))), + ( + "stroke".to_string(), + SessionValue::Any(color_any("#929292", "#929292")), + ), + ( + "strokeWidth".to_string(), + SessionValue::Any(Any::Integer(4)), + ), + ( + "strokeStyle".to_string(), + SessionValue::Any(Any::String("solid".to_string())), + ), + ( + "roughness".to_string(), + SessionValue::Any(Any::Float64(DEFAULT_ROUGHNESS.into())), + ), + ( + "frontEndpointStyle".to_string(), + SessionValue::Any(Any::String("None".to_string())), + ), + ( + "rearEndpointStyle".to_string(), + SessionValue::Any(Any::String("Arrow".to_string())), + ), + ("source".to_string(), SessionValue::Any(source.to_any())), + ("target".to_string(), SessionValue::Any(target.to_any())), + ("labelDisplay".to_string(), SessionValue::Any(Any::True)), + ( + "labelConstraints".to_string(), + SessionValue::Any(Any::Object(Box::new(label_constraints))), + ), + ( + "labelOffset".to_string(), + SessionValue::Any(Any::Object(Box::new(label_offset))), + ), + ( + "labelStyle".to_string(), + SessionValue::Any(Any::Object(Box::new(label_style))), + ), + ]); + if let Some(text_str) = text { + entries.push(("text".to_string(), text_value(&text_str))); + } + if let Some([x, y, w, h]) = label_xywh { + entries.push(( + "labelXYWH".to_string(), + SessionValue::Any(map_array_any(vec![ + Any::Float64(x.into()), + Any::Float64(y.into()), + Any::Float64(w.into()), + Any::Float64(h.into()), + ])), + )); + } + } + Self::Brush { seed, points, xywh } => { + let any_points = map_array_any( + points + .into_iter() + .map(|pt| { + Any::Array(pt.into_iter().map(|v| Any::Float64(v.into())).collect()) + }) + .collect(), + ); + entries.extend([ + ( + "seed".to_string(), + SessionValue::Any(Any::Integer(nonzero_seed(seed))), + ), + ( + "color".to_string(), + SessionValue::Any(color_any("#ffffff", "#000000")), + ), + ("lineWidth".to_string(), SessionValue::Any(Any::Integer(4))), + ("points".to_string(), SessionValue::Any(any_points)), + ("rotate".to_string(), SessionValue::Any(Any::Integer(0))), + ("xywh".to_string(), SessionValue::Any(Any::String(xywh))), + ]); + } + Self::Highlighter { seed, points, xywh } => { + let any_points = map_array_any( + points + .into_iter() + .map(|pt| { + Any::Array(pt.into_iter().map(|v| Any::Float64(v.into())).collect()) + }) + .collect(), + ); + entries.extend([ + ( + "seed".to_string(), + SessionValue::Any(Any::Integer(nonzero_seed(seed))), + ), + ( + "color".to_string(), + SessionValue::Any(Any::String("#84cfff4d".to_string())), + ), + ( + "lineWidth".to_string(), + SessionValue::Any(Any::Float64(DEFAULT_HIGHLIGHTER_LINE_WIDTH.into())), + ), + ("points".to_string(), SessionValue::Any(any_points)), + ("rotate".to_string(), SessionValue::Any(Any::Integer(0))), + ("xywh".to_string(), SessionValue::Any(Any::String(xywh))), + ]); + } + Self::Text { seed, text, xywh } => { + entries.extend([ + ( + "seed".to_string(), + SessionValue::Any(Any::Integer(nonzero_seed(seed))), + ), + ( + "color".to_string(), + SessionValue::Any(color_any("#ffffff", "#000000")), + ), + ( + "fontFamily".to_string(), + SessionValue::Any(Any::String("blocksuite:surface:Inter".to_string())), + ), + ("fontSize".to_string(), SessionValue::Any(Any::Integer(16))), + ( + "fontStyle".to_string(), + SessionValue::Any(Any::String("normal".to_string())), + ), + ( + "fontWeight".to_string(), + SessionValue::Any(Any::String("400".to_string())), + ), + ("hasMaxWidth".to_string(), SessionValue::Any(Any::False)), + ("rotate".to_string(), SessionValue::Any(Any::Integer(0))), + ("text".to_string(), text_value(&text)), + ( + "textAlign".to_string(), + SessionValue::Any(Any::String("center".to_string())), + ), + ("xywh".to_string(), SessionValue::Any(Any::String(xywh))), + ]); + } + Self::Group { + seed, + title, + children, + } => { + let child_entries = children + .into_iter() + .map(|cid| (cid, SessionValue::Any(Any::True))) + .collect(); + entries.extend([ + ( + "seed".to_string(), + SessionValue::Any(Any::Integer(nonzero_seed(seed))), + ), + ("children".to_string(), SessionValue::Map(child_entries)), + ("title".to_string(), text_value(&title)), + ]); + } + } + + entries + } +} diff --git a/blocksuite/native-playground/crates/doc/src/session.rs b/blocksuite/native-playground/crates/doc/src/session.rs new file mode 100644 index 0000000000..5d6ba4d43e --- /dev/null +++ b/blocksuite/native-playground/crates/doc/src/session.rs @@ -0,0 +1,848 @@ +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; +use serde_json::{Map as JsonMap, Value as JsonValue}; +use y_octo::{ + Any, DocOptions, DocSession, RelativePosition, SessionCommit, SessionConfig, SessionOriginKind, + SessionReadValue, SessionTxOrigin, SessionUndoConfig, SessionValue, TextAttributes, + TextDeltaOp, TextInsert, TypePath, TypeTarget, UndoStackId, YTypeKind, +}; + +use crate::{ + DocError, DocResult, + schema::{BlockSpec, SurfaceElementSpec, UnknownBlock, affine_block_versions}, + validate_client_id, +}; + +/// Default Undo capture merge timeout (500ms) driven by explicit `now_ms`. +pub const DEFAULT_UNDO_CAPTURE_TIMEOUT_MS: u64 = 500; + +/// Relative-position selection snapshot stored on the page's undo stack. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SelectionSnapshot { + pub anchor_block_id: String, + pub anchor: RelativePosition, + pub focus_block_id: String, + pub focus: RelativePosition, +} + +/// Result of applying a remote V1 update to a session. +#[derive(Debug, Clone)] +pub struct RemoteApplyResult { + pub commits: Vec>, + /// Any local `FormattingCleanup` commits produced during integration that + /// MUST be forwarded to outbound sync. + pub outbound_updates: Vec>, +} + +/// Page metadata entry stored in the workspace root `meta.pages` `Y.Array`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PageMeta { + pub id: String, + pub title: String, + pub create_date: i64, + pub tags: Vec, +} + +/// Per-page CRDT session wrapping `DocSession` with an +/// `UndoStackId` scoped strictly to the `blocks` root `Y.Map`. +pub struct PageDocSession { + session: DocSession, + undo_stack_id: UndoStackId, + blocks_target: TypeTarget, +} + +impl PageDocSession { + pub fn new(page_id: impl Into, client_id: u64) -> DocResult { + let client_id = validate_client_id(client_id)?; + let options = DocOptions::from_identity(client_id, page_id.into()); + let mut session = DocSession::with_config( + options, + SessionConfig { + undo: SessionUndoConfig::Custom, + }, + ); + let blocks_id = session.ensure_root("blocks", YTypeKind::Map)?; + let blocks_target = TypeTarget::from(blocks_id); + let undo_stack_id = session.create_undo_stack( + std::slice::from_ref(&blocks_target), + DEFAULT_UNDO_CAPTURE_TIMEOUT_MS, + &[SessionTxOrigin::Tracked], + )?; + Ok(Self { + session, + undo_stack_id, + blocks_target, + }) + } + + pub fn guid(&self) -> &str { + self.session.guid() + } + + pub fn client_id(&self) -> u64 { + self.session.client() + } + + pub fn undo_stack_id(&self) -> UndoStackId { + self.undo_stack_id + } + + pub fn inner(&self) -> &DocSession { + &self.session + } + + pub fn inner_mut(&mut self) -> &mut DocSession { + &mut self.session + } + + pub fn advance_time(&self, now_ms: u64) { + self.session.advance_time(now_ms); + } + + pub fn encode_state_vector_v1(&self) -> DocResult> { + Ok(self.session.encode_state_vector_v1()?) + } + + pub fn encode_update_v1(&self) -> DocResult> { + Ok(self.session.encode_update_v1()?) + } + + pub fn encode_diff_v1(&self, remote_sv: &[u8]) -> DocResult> { + Ok(self.session.encode_diff_v1(remote_sv)?) + } + + /// Apply a remote V1 update and collect any secondary `FormattingCleanup` + /// commits so the caller can broadcast them back to the room. + pub fn apply_remote_update_v1(&mut self, bytes: &[u8]) -> DocResult { + let commits = self.session.apply_update_v1(bytes)?; + let outbound_updates = commits + .iter() + .filter(|c| { + c.origin_kind == SessionOriginKind::FormattingCleanup && !c.update.is_empty() + }) + .map(|c| c.update.clone()) + .collect(); + Ok(RemoteApplyResult { + commits, + outbound_updates, + }) + } + + /// Add a typed Phase-1 block with all BlockSuite default properties populated. + /// If `parent_id` is `Some`, appends `block_id` to `parent.sys:children` (or inserts at `index`). + pub fn add_block( + &mut self, + block_id: impl Into, + spec: BlockSpec, + parent_id: Option<&str>, + index: Option, + now_ms: u64, + ) -> DocResult>> { + if let Some(pid) = parent_id { + let parent_target = TypeTarget::Path(TypePath::root("blocks").key(pid)); + let children_val = self + .session + .get_map_value(&parent_target, "sys:children") + .map_err(|_| DocError::BlockNotFound(pid.to_string()))?; + let Some(SessionReadValue::Array(children_id)) = children_val else { + return Err(DocError::BlockNotFound(pid.to_string())); + }; + if let Some(idx) = index { + let len = self + .session + .read_array(&TypeTarget::Identity(children_id))? + .len() as u64; + if idx > len { + return Err(DocError::Codec(y_octo::JwstCodecError::IndexOutOfBound( + idx, + ))); + } + } + } + + self.session.advance_time(now_ms); + let block_id = block_id.into(); + let entries = spec.into_yblock_entries(&block_id); + + self.session.begin_tx(SessionTxOrigin::Tracked)?; + self.session.map_set( + &self.blocks_target, + block_id.clone(), + SessionValue::Map(entries), + )?; + if let Some(pid) = parent_id { + let children_target = + TypeTarget::Path(TypePath::root("blocks").key(pid).key("sys:children")); + let child_val = vec![SessionValue::Any(Any::String(block_id))]; + match index { + Some(idx) => { + self.session + .array_insert(&children_target, idx, child_val)?; + } + None => { + self.session.array_push(&children_target, child_val)?; + } + } + } + Ok(self.session.commit_tx()?) + } + + /// Move an existing child block to a new index within `parent_id`'s `sys:children`. + pub fn reorder_child( + &mut self, + parent_id: &str, + child_id: &str, + new_index: u64, + now_ms: u64, + ) -> DocResult>> { + self.session.advance_time(now_ms); + let children_target = + TypeTarget::Path(TypePath::root("blocks").key(parent_id).key("sys:children")); + let items = self.session.read_array(&children_target)?; + let old_pos = items + .iter() + .position(|v| matches!(v, SessionReadValue::Any(Any::String(s)) if s == child_id)) + .ok_or_else(|| DocError::BlockNotFound(child_id.to_string()))?; + let clamped_index = new_index.min((items.len().saturating_sub(1)) as u64); + + self.session.begin_tx(SessionTxOrigin::Tracked)?; + self.session + .array_remove(&children_target, old_pos as u64, 1)?; + self.session.array_insert( + &children_target, + clamped_index, + vec![SessionValue::Any(Any::String(child_id.to_string()))], + )?; + Ok(self.session.commit_tx()?) + } + + /// Insert text into a block's `Y.Text` property (e.g. `"prop:text"` or `"prop:title"`). + pub fn insert_text( + &mut self, + block_id: &str, + prop_key: &str, + index: u64, + text: &str, + now_ms: u64, + ) -> DocResult>> { + self.session.advance_time(now_ms); + let target = TypeTarget::Path(TypePath::root("blocks").key(block_id).key(prop_key)); + Ok(self.session.text_insert(&target, index, text)?) + } + + /// Remove a UTF-16 range from a block's `Y.Text` property. + pub fn remove_text( + &mut self, + block_id: &str, + prop_key: &str, + index: u64, + len: u64, + now_ms: u64, + ) -> DocResult>> { + self.session.advance_time(now_ms); + let target = TypeTarget::Path(TypePath::root("blocks").key(block_id).key(prop_key)); + Ok(self.session.text_remove(&target, index, len)?) + } + + /// Apply formatting attributes to a range in a block's `Y.Text` property. + pub fn format_text( + &mut self, + block_id: &str, + prop_key: &str, + index: u64, + len: u64, + attrs: TextAttributes, + now_ms: u64, + ) -> DocResult>> { + self.session.advance_time(now_ms); + let target = TypeTarget::Path(TypePath::root("blocks").key(block_id).key(prop_key)); + Ok(self.session.text_format(&target, index, len, attrs)?) + } + + /// Apply a raw delta to a block's `Y.Text` property. + pub fn apply_text_delta( + &mut self, + block_id: &str, + prop_key: &str, + delta: &[TextDeltaOp], + now_ms: u64, + ) -> DocResult>> { + self.session.advance_time(now_ms); + let target = TypeTarget::Path(TypePath::root("blocks").key(block_id).key(prop_key)); + Ok(self.session.text_apply_delta(&target, delta)?) + } + + /// Set a scalar or nested property on a block (`prop:*`). + pub fn set_block_prop( + &mut self, + block_id: &str, + prop_key: impl Into, + value: SessionValue, + now_ms: u64, + ) -> DocResult>> { + self.session.advance_time(now_ms); + let target = TypeTarget::Path(TypePath::root("blocks").key(block_id)); + Ok(self.session.map_set(&target, prop_key.into(), value)?) + } + + /// Add a surface element inside `surface_block_id`'s `prop:elements.value` `Y.Map`. + pub fn add_surface_element( + &mut self, + surface_block_id: &str, + element_id: impl Into, + index: &str, + spec: SurfaceElementSpec, + now_ms: u64, + ) -> DocResult>> { + self.session.advance_time(now_ms); + let element_id = element_id.into(); + let entries = spec.into_ymap_entries(&element_id, index); + let elements_value_target = TypeTarget::Path( + TypePath::root("blocks") + .key(surface_block_id) + .key("prop:elements") + .key("value"), + ); + Ok(self.session.map_set( + &elements_value_target, + element_id, + SessionValue::Map(entries), + )?) + } + + /// Update a field on an existing surface element. + pub fn set_surface_element_field( + &mut self, + surface_block_id: &str, + element_id: &str, + field: impl Into, + value: SessionValue, + now_ms: u64, + ) -> DocResult>> { + self.session.advance_time(now_ms); + let target = TypeTarget::Path( + TypePath::root("blocks") + .key(surface_block_id) + .key("prop:elements") + .key("value") + .key(element_id), + ); + Ok(self.session.map_set(&target, field.into(), value)?) + } + + /// Capture a relative-position selection snapshot on a text property and attach + /// it to the top undo item of this page's `blocks` undo stack. + pub fn capture_selection_snapshot( + &self, + anchor_block_id: &str, + anchor_offset: u64, + focus_block_id: &str, + focus_offset: u64, + ) -> DocResult { + let anchor_target = TypeTarget::Path( + TypePath::root("blocks") + .key(anchor_block_id) + .key("prop:text"), + ); + let focus_target = TypeTarget::Path( + TypePath::root("blocks") + .key(focus_block_id) + .key("prop:text"), + ); + let anchor = self + .session + .create_relative_position(&anchor_target, anchor_offset, 0)?; + let focus = self + .session + .create_relative_position(&focus_target, focus_offset, 0)?; + Ok(SelectionSnapshot { + anchor_block_id: anchor_block_id.to_string(), + anchor, + focus_block_id: focus_block_id.to_string(), + focus, + }) + } + + pub fn set_undo_selection_snapshot(&self, snapshot: SelectionSnapshot) -> DocResult { + Ok(self.session.set_stack_selection_meta( + self.undo_stack_id, + y_octo::UndoStack::Undo, + snapshot, + )?) + } + + pub fn undo(&mut self) -> DocResult>> { + Ok(self.session.undo_stack(self.undo_stack_id)?) + } + + pub fn redo(&mut self) -> DocResult>> { + Ok(self.session.redo_stack(self.undo_stack_id)?) + } + + pub fn can_undo(&self) -> bool { + self.session.can_undo_stack(self.undo_stack_id) + } + + pub fn can_redo(&self) -> bool { + self.session.can_redo_stack(self.undo_stack_id) + } + + pub fn stop_capturing(&mut self) -> DocResult { + Ok(self.session.stop_capturing_stack(self.undo_stack_id)?) + } + + /// Read a block as a lossless [`UnknownBlock`] descriptor without mutating its Y.Map. + pub fn read_unknown_block(&self, block_id: &str) -> DocResult { + let block_target = TypeTarget::Path(TypePath::root("blocks").key(block_id)); + let entries = self + .session + .read_map(&block_target) + .map_err(|_| DocError::BlockNotFound(block_id.to_string()))?; + + let mut id = block_id.to_string(); + let mut flavour = String::new(); + let mut version = None; + let mut children = Vec::new(); + let mut prop_keys = Vec::new(); + + for (k, v) in entries { + match k.as_str() { + "sys:id" => { + if let SessionReadValue::Any(Any::String(s)) = v { + id = s; + } + } + "sys:flavour" => { + if let SessionReadValue::Any(Any::String(s)) = v { + flavour = s; + } + } + "sys:version" => { + if let SessionReadValue::Any(Any::Integer(n)) = v { + version = Some(i64::from(n)); + } else if let SessionReadValue::Any(Any::Float64(f)) = v { + version = Some(f.0 as i64); + } + } + "sys:children" => { + if let SessionReadValue::Array(arr_id) = v { + let arr = self.session.read_array(&TypeTarget::Identity(arr_id))?; + for item in arr { + if let SessionReadValue::Any(Any::String(s)) = item { + children.push(s); + } + } + } + } + key if key.starts_with("prop:") => { + prop_keys.push(key.to_string()); + } + _ => {} + } + } + prop_keys.sort(); + + Ok(UnknownBlock { + id, + flavour, + version, + children, + prop_keys, + }) + } + + /// Export a normalized JSON representation matching BlockSuite's snapshot structure + /// for L0 oracle convergence assertions. + pub fn export_doc_json(&self) -> DocResult { + let blocks = self.session.read_map(&self.blocks_target)?; + let mut out_blocks = JsonMap::new(); + for (block_id, val) in blocks { + if let SessionReadValue::Map(map_id) = val { + out_blocks.insert( + block_id, + self.export_y_value(&SessionReadValue::Map(map_id))?, + ); + } + } + let mut root = JsonMap::new(); + root.insert( + "guid".to_string(), + JsonValue::String(self.guid().to_string()), + ); + root.insert("blocks".to_string(), JsonValue::Object(out_blocks)); + Ok(JsonValue::Object(root)) + } + + fn export_y_value(&self, value: &SessionReadValue) -> DocResult { + match value { + SessionReadValue::Any(any) => Ok(any_to_normalized_json(any)), + SessionReadValue::Map(id) => { + let entries = self.session.read_map(&TypeTarget::Identity(id.clone()))?; + let mut map = JsonMap::new(); + for (k, v) in entries { + map.insert(k, self.export_y_value(&v)?); + } + Ok(JsonValue::Object(map)) + } + SessionReadValue::Array(id) => { + let items = self.session.read_array(&TypeTarget::Identity(id.clone()))?; + let mut arr = Vec::with_capacity(items.len()); + for item in items { + arr.push(self.export_y_value(&item)?); + } + Ok(JsonValue::Array(arr)) + } + SessionReadValue::Text(id) => { + let delta = self + .session + .read_text_delta(&TypeTarget::Identity(id.clone()))?; + let mut ops: Vec = Vec::with_capacity(delta.len()); + for op in delta { + if let TextDeltaOp::Insert { insert, format } = op { + let attrs_obj = format.filter(|a| !a.is_empty()).map(|attrs| { + let mut attr_map = JsonMap::new(); + for (k, v) in attrs { + attr_map.insert(k, any_to_normalized_json(&v)); + } + JsonValue::Object(attr_map) + }); + + if let TextInsert::Text(s) = insert { + // Coalesce adjacent string inserts with identical attributes (matching Yjs toDelta()). + if let Some(JsonValue::Object(prev)) = ops.last_mut() + && prev.get("attributes") == attrs_obj.as_ref() + && let Some(JsonValue::String(prev_s)) = prev.get_mut("insert") + { + prev_s.push_str(&s); + continue; + } + let mut obj = JsonMap::new(); + obj.insert("insert".to_string(), JsonValue::String(s)); + if let Some(a) = attrs_obj { + obj.insert("attributes".to_string(), a); + } + ops.push(JsonValue::Object(obj)); + } else if let TextInsert::Embed(items) = insert { + let embed_val = if items.len() == 1 { + any_to_normalized_json(&items[0]) + } else { + JsonValue::Array(items.iter().map(any_to_normalized_json).collect()) + }; + let mut obj = JsonMap::new(); + obj.insert("insert".to_string(), embed_val); + if let Some(a) = attrs_obj { + obj.insert("attributes".to_string(), a); + } + ops.push(JsonValue::Object(obj)); + } + } + } + Ok(JsonValue::Array(ops)) + } + SessionReadValue::Doc { guid, .. } => Ok(JsonValue::String(guid.clone())), + SessionReadValue::XmlElement { identity, .. } + | SessionReadValue::XmlFragment(identity) + | SessionReadValue::XmlText(identity) => { + let s = self + .session + .xml_to_string(&TypeTarget::Identity(identity.clone()))?; + Ok(JsonValue::String(s)) + } + SessionReadValue::XmlHook { name, .. } => Ok(JsonValue::String(name.clone())), + } + } +} + +/// Normalize `y_octo::Any` to canonical `serde_json::Value` (integral floats become integers, +/// map keys sorted). +pub fn any_to_normalized_json(any: &Any) -> JsonValue { + match any { + Any::Null | Any::Undefined => JsonValue::Null, + Any::True => JsonValue::Bool(true), + Any::False => JsonValue::Bool(false), + Any::Integer(i) => JsonValue::Number((*i).into()), + Any::BigInt64(i) => JsonValue::Number((*i).into()), + Any::Float32(f) => float_to_json(f64::from(f.0)), + Any::Float64(f) => float_to_json(f.0), + Any::String(s) => JsonValue::String(s.clone()), + Any::Binary(b) => { + JsonValue::Array(b.iter().map(|&x| JsonValue::Number(x.into())).collect()) + } + Any::Array(items) => JsonValue::Array(items.iter().map(any_to_normalized_json).collect()), + Any::Object(map) => { + let mut sorted: Vec<(&String, &Any)> = map.iter().collect(); + sorted.sort_by_key(|(a, _)| *a); + let mut obj = JsonMap::new(); + for (k, v) in sorted { + obj.insert(k.clone(), any_to_normalized_json(v)); + } + JsonValue::Object(obj) + } + } +} + +fn float_to_json(f: f64) -> JsonValue { + if f.is_finite() && f.fract() == 0.0 && f >= (i64::MIN as f64) && f <= (i64::MAX as f64) { + JsonValue::Number((f as i64).into()) + } else { + serde_json::Number::from_f64(f).map_or(JsonValue::Null, JsonValue::Number) + } +} + +/// Multi-document workspace session owning the root room `DocSession` (`meta`, `spaces`) +/// and per-page [`PageDocSession`]s. +pub struct WorkspaceSession { + room: String, + client_id: u64, + root: DocSession<()>, + meta_target: TypeTarget, + spaces_target: TypeTarget, + pages: BTreeMap, +} + +impl WorkspaceSession { + pub fn new(room: impl Into, client_id: u64) -> DocResult { + let client_id = validate_client_id(client_id)?; + let room = room.into(); + let options = DocOptions::from_identity(client_id, room.clone()); + let mut root = DocSession::with_config( + options, + SessionConfig { + undo: SessionUndoConfig::Disabled, + }, + ); + let meta_id = root.ensure_root("meta", YTypeKind::Map)?; + let spaces_id = root.ensure_root("spaces", YTypeKind::Map)?; + Ok(Self { + room, + client_id, + root, + meta_target: TypeTarget::from(meta_id), + spaces_target: TypeTarget::from(spaces_id), + pages: BTreeMap::new(), + }) + } + + pub fn room(&self) -> &str { + &self.room + } + + pub fn client_id(&self) -> u64 { + self.client_id + } + + pub fn root(&self) -> &DocSession<()> { + &self.root + } + + pub fn root_mut(&mut self) -> &mut DocSession<()> { + &mut self.root + } + + /// Initialize workspace `meta` with `pages: YArray` and `blockVersions` matching `AffineSchemas`. + pub fn initialize_meta(&mut self) -> DocResult>> { + self.root.begin_tx(SessionTxOrigin::Untracked)?; + if self + .root + .get_map_value(&self.meta_target, "pages")? + .is_none() + { + self.root.map_set( + &self.meta_target, + "pages".to_string(), + SessionValue::Array(Vec::new()), + )?; + } + if self + .root + .get_map_value(&self.meta_target, "blockVersions")? + .is_none() + { + let version_entries = affine_block_versions() + .into_iter() + .map(|(flavour, ver)| (flavour.to_string(), SessionValue::Any(Any::Integer(ver)))) + .collect(); + self.root.map_set( + &self.meta_target, + "blockVersions".to_string(), + SessionValue::Map(version_entries), + )?; + } + Ok(self.root.commit_tx()?) + } + + /// Register a new page in root `meta.pages` and `spaces`, and create its local [`PageDocSession`]. + pub fn create_page( + &mut self, + page_id: impl Into, + title: impl Into, + create_date: i64, + ) -> DocResult>> { + let page_id = page_id.into(); + let title = title.into(); + + self.root.begin_tx(SessionTxOrigin::Untracked)?; + if self + .root + .get_map_value(&self.meta_target, "pages")? + .is_none() + { + self.root.map_set( + &self.meta_target, + "pages".to_string(), + SessionValue::Array(Vec::new()), + )?; + } + let pages_target = TypeTarget::Path(TypePath::root("meta").key("pages")); + let page_meta_map = SessionValue::Map(vec![ + ( + "id".to_string(), + SessionValue::Any(Any::String(page_id.clone())), + ), + ("title".to_string(), SessionValue::Any(Any::String(title))), + ( + "createDate".to_string(), + SessionValue::Any(Any::Float64((create_date as f64).into())), + ), + ("tags".to_string(), SessionValue::Array(Vec::new())), + ]); + self.root.array_push(&pages_target, vec![page_meta_map])?; + self.root.map_set( + &self.spaces_target, + page_id.clone(), + SessionValue::Doc { + guid: page_id.clone(), + gc: true, + }, + )?; + let commit = self.root.commit_tx()?; + + if !self.pages.contains_key(&page_id) { + let page_session = PageDocSession::new(page_id.clone(), self.client_id)?; + self.pages.insert(page_id, page_session); + } + Ok(commit) + } + + /// Ensure a local [`PageDocSession`] exists for `page_id` (e.g. discovered via remote root sync). + pub fn ensure_page(&mut self, page_id: &str) -> DocResult<&mut PageDocSession> { + if !self.pages.contains_key(page_id) { + let session = PageDocSession::new(page_id.to_string(), self.client_id)?; + self.pages.insert(page_id.to_string(), session); + } + self.pages + .get_mut(page_id) + .ok_or_else(|| DocError::PageNotFound(page_id.to_string())) + } + + pub fn page(&self, page_id: &str) -> Option<&PageDocSession> { + self.pages.get(page_id) + } + + pub fn page_mut(&mut self, page_id: &str) -> Option<&mut PageDocSession> { + self.pages.get_mut(page_id) + } + + /// Apply a remote update to the root workspace doc and auto-instantiate any newly added subdocs. + pub fn apply_root_update_v1(&mut self, bytes: &[u8]) -> DocResult> { + let commits = self.root.apply_update_v1(bytes)?; + let mut subdoc_ids = Vec::new(); + for c in &commits { + subdoc_ids.extend(c.subdocs_added.iter().cloned()); + } + for id in subdoc_ids { + let _ = self.ensure_page(&id)?; + } + let outbound_updates = commits + .iter() + .filter(|c| { + c.origin_kind == SessionOriginKind::FormattingCleanup && !c.update.is_empty() + }) + .map(|c| c.update.clone()) + .collect(); + Ok(RemoteApplyResult { + commits, + outbound_updates, + }) + } + + /// Read all page metadata entries currently in `meta.pages`. + pub fn list_pages(&self) -> DocResult> { + 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 { + if let SessionReadValue::Map(map_id) = item { + let entries = self.root.read_map(&TypeTarget::Identity(map_id))?; + let mut id = String::new(); + let mut title = String::new(); + let mut create_date = 0i64; + let mut tags = Vec::new(); + for (k, v) in entries { + match k.as_str() { + "id" => { + if let SessionReadValue::Any(Any::String(s)) = v { + id = s; + } + } + "title" => { + if let SessionReadValue::Any(Any::String(s)) = v { + title = s; + } + } + "createDate" => match v { + SessionReadValue::Any(Any::Integer(n)) => create_date = i64::from(n), + SessionReadValue::Any(Any::Float64(f)) => create_date = f.0 as i64, + _ => {} + }, + "tags" => { + if let SessionReadValue::Array(arr_id) = v { + for tag in self.root.read_array(&TypeTarget::Identity(arr_id))? { + if let SessionReadValue::Any(Any::String(s)) = tag { + tags.push(s); + } + } + } + } + _ => {} + } + } + if !id.is_empty() { + result.push(PageMeta { + id, + title, + create_date, + tags, + }); + } + } + } + Ok(result) + } + + /// Encode state vector for either the root workspace doc (`doc_id == room`) or a page subdoc. + pub fn encode_state_vector_v1(&self, doc_id: &str) -> DocResult> { + if doc_id == self.room { + Ok(self.root.encode_state_vector_v1()?) + } else { + self.page(doc_id) + .ok_or_else(|| DocError::PageNotFound(doc_id.to_string()))? + .encode_state_vector_v1() + } + } + + /// Encode diff for either the root workspace doc or a page subdoc. + pub fn encode_diff_v1(&self, doc_id: &str, remote_sv: &[u8]) -> DocResult> { + if doc_id == self.room { + Ok(self.root.encode_diff_v1(remote_sv)?) + } else { + self.page(doc_id) + .ok_or_else(|| DocError::PageNotFound(doc_id.to_string()))? + .encode_diff_v1(remote_sv) + } + } +} diff --git a/blocksuite/native-playground/crates/doc/src/wire.rs b/blocksuite/native-playground/crates/doc/src/wire.rs new file mode 100644 index 0000000000..dbff838227 --- /dev/null +++ b/blocksuite/native-playground/crates/doc/src/wire.rs @@ -0,0 +1,188 @@ +use serde::{Deserialize, Serialize}; +pub use y_octo::DocMessage; +use y_octo::{ + SyncMessage, read_sync_message, read_var_string, write_sync_message, write_var_string, +}; + +use crate::{DocError, DocResult}; + +/// Binary frame tag for document sync frames (`varString(docId) + y-protocols SyncMessage::Doc`). +pub const FRAME_TAG_DOC: u8 = 0x00; + +/// Binary frame tag for awareness frames (`y-protocols/awareness` binary update). +pub const FRAME_TAG_AWARENESS: u8 = 0x01; + +/// Decoded binary room frame exchanged over `/native-sync/rooms/:room`. +#[derive(Debug, Clone, PartialEq)] +pub enum RoomBinaryFrame { + Doc { doc_id: String, message: DocMessage }, + Awareness(Vec), +} + +/// JSON text control frames exchanged over `/native-sync/rooms/:room`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "kebab-case")] +pub enum RoomControlFrame { + /// Request single-winner CAS ownership for initial room seeding. + SeedClaim { key: String }, + /// Hub response to `SeedClaim`. + SeedClaimResult { key: String, winner: bool }, + /// Hub acknowledgement once reverse `Step2` for `doc_id` has been applied. + Ready { + #[serde(rename = "docId")] + doc_id: String, + }, +} + +/// Encode a binary room frame for WebSocket transmission. +pub fn encode_binary_frame(frame: &RoomBinaryFrame) -> DocResult> { + let mut out = Vec::new(); + match frame { + RoomBinaryFrame::Doc { doc_id, message } => { + out.push(FRAME_TAG_DOC); + write_var_string(&mut out, doc_id).map_err(|e| DocError::Wire(e.to_string()))?; + write_sync_message(&mut out, &SyncMessage::Doc(message.clone())) + .map_err(|e| DocError::Wire(e.to_string()))?; + } + RoomBinaryFrame::Awareness(payload) => { + out.push(FRAME_TAG_AWARENESS); + out.extend_from_slice(payload); + } + } + Ok(out) +} + +/// Decode a binary room frame received from WebSocket. +pub fn decode_binary_frame(bytes: &[u8]) -> DocResult { + let (&tag, rest) = bytes + .split_first() + .ok_or_else(|| DocError::Wire("empty binary frame".to_string()))?; + match tag { + FRAME_TAG_DOC => { + let (tail, doc_id) = read_var_string(rest) + .map_err(|e| DocError::Wire(format!("invalid doc_id varString: {e}")))?; + let (remaining, sync_msg) = read_sync_message(tail) + .map_err(|e| DocError::Wire(format!("invalid y-protocols sync message: {e}")))?; + if !remaining.is_empty() { + return Err(DocError::Wire(format!( + "trailing bytes in doc frame: {}", + remaining.len() + ))); + } + match sync_msg { + SyncMessage::Doc(message) => Ok(RoomBinaryFrame::Doc { doc_id, message }), + other => Err(DocError::Wire(format!( + "expected SyncMessage::Doc inside doc frame, got {other:?}" + ))), + } + } + FRAME_TAG_AWARENESS => Ok(RoomBinaryFrame::Awareness(rest.to_vec())), + other => Err(DocError::Wire(format!( + "unknown binary frame tag: 0x{other:02x}" + ))), + } +} + +/// Encode a text JSON control frame. +pub fn encode_control_frame(frame: &RoomControlFrame) -> DocResult { + Ok(serde_json::to_string(frame)?) +} + +/// Decode a text JSON control frame. +pub fn decode_control_frame(text: &str) -> DocResult { + Ok(serde_json::from_str(text)?) +} + +/// Per-document client-side sync state machine (Sans-I/O, Wasm-compatible). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DocSyncPhase { + Idle, + Pulling, + Synced, +} + +/// Pure client-side handshake tracker for a single document. +#[derive(Debug, Clone)] +pub struct DocSyncState { + doc_id: String, + phase: DocSyncPhase, + pending_remote_sv: Option>, + received_step2: bool, +} + +impl DocSyncState { + pub fn new(doc_id: impl Into) -> Self { + Self { + doc_id: doc_id.into(), + phase: DocSyncPhase::Idle, + pending_remote_sv: None, + received_step2: false, + } + } + + pub fn doc_id(&self) -> &str { + &self.doc_id + } + + pub fn phase(&self) -> DocSyncPhase { + self.phase + } + + /// Begin handshake by emitting `Step1(local_sv)`. + pub fn begin_pull(&mut self, local_sv: Vec) -> RoomBinaryFrame { + self.phase = DocSyncPhase::Pulling; + self.received_step2 = false; + self.pending_remote_sv = None; + RoomBinaryFrame::Doc { + doc_id: self.doc_id.clone(), + message: DocMessage::Step1(local_sv), + } + } + + /// Reset handshake state on disconnect so reconnect starts cleanly. + pub fn on_disconnect(&mut self) { + self.phase = DocSyncPhase::Idle; + self.received_step2 = false; + self.pending_remote_sv = None; + } + + /// Record receipt of hub's `Step2` diff. Returns `Some(remote_sv)` once both + /// hub's `Step2` and reverse `Step1(remote_sv)` have arrived. + pub fn on_hub_step2(&mut self) -> Option> { + self.received_step2 = true; + if let Some(sv) = self.pending_remote_sv.take() { + self.phase = DocSyncPhase::Synced; + Some(sv) + } else { + None + } + } + + /// Record receipt of hub's reverse `Step1(remote_sv)`. Returns `Some(remote_sv)` + /// once both hub's `Step2` and reverse `Step1(remote_sv)` have arrived. + pub fn on_hub_step1(&mut self, remote_sv: Vec) -> Option> { + if self.received_step2 { + self.phase = DocSyncPhase::Synced; + Some(remote_sv) + } else { + self.pending_remote_sv = Some(remote_sv); + None + } + } + + /// Build the unconditional reverse `Step2(diff_to_hub)` frame (even when empty `[0, 0]`). + pub fn build_reverse_step2(&self, diff_to_hub: Vec) -> RoomBinaryFrame { + RoomBinaryFrame::Doc { + doc_id: self.doc_id.clone(), + message: DocMessage::Step2(diff_to_hub), + } + } + + /// Build an incremental `Update(bytes)` frame. + pub fn build_update(&self, update: Vec) -> RoomBinaryFrame { + RoomBinaryFrame::Doc { + doc_id: self.doc_id.clone(), + message: DocMessage::Update(update), + } + } +} diff --git a/blocksuite/native-playground/crates/doc/tests/doc_room_sync.rs b/blocksuite/native-playground/crates/doc/tests/doc_room_sync.rs new file mode 100644 index 0000000000..c916257eb5 --- /dev/null +++ b/blocksuite/native-playground/crates/doc/tests/doc_room_sync.rs @@ -0,0 +1,1126 @@ +#![forbid(unsafe_code)] + +use std::net::SocketAddr; + +use blocksuite_playground_doc::{ + MAX_JS_CLIENT_ID, + awareness::{ + AWARENESS_EXPIRE_TIMEOUT_MS, AWARENESS_RENEW_INTERVAL_MS, AwarenessPayload, RoomAwareness, + }, + client_id_from_seed, + room::RoomHub, + schema::{BlockSpec, ConnectorEndpointSpec, ListType, ParagraphType, SurfaceElementSpec}, + session::{PageDocSession, WorkspaceSession}, + validate_client_id, + wire::{ + DocSyncPhase, DocSyncState, RoomBinaryFrame, RoomControlFrame, decode_binary_frame, + decode_control_frame, encode_binary_frame, encode_control_frame, + }, +}; +use futures_util::{SinkExt, StreamExt}; +use proptest::prelude::*; +use rand::{Rng, SeedableRng}; +use rand_chacha::ChaCha8Rng; +use tokio::net::TcpListener; +use tokio_tungstenite::{connect_async, tungstenite::Message as WsMsg}; +use y_octo::{Any, DocMessage, SessionValue, StateVector, TextAttributes}; + +#[test] +fn client_id_53_bit_contract() { + assert!(validate_client_id(0).is_err()); + assert!(validate_client_id(MAX_JS_CLIENT_ID + 1).is_err()); + assert_eq!( + validate_client_id(MAX_JS_CLIENT_ID).unwrap(), + MAX_JS_CLIENT_ID + ); + + let high_id = (1u64 << 40) + 12345; + assert_eq!(validate_client_id(high_id).unwrap(), high_id); + + let mut page = PageDocSession::new("doc:high-id", high_id).unwrap(); + assert_eq!(page.client_id(), high_id); + page.add_block( + "root", + BlockSpec::Page { + title: "High Client ID".to_string(), + }, + None, + None, + 100, + ) + .unwrap(); + + let sv_bytes = page.encode_state_vector_v1().unwrap(); + let sv = StateVector::decode_v1(&sv_bytes).unwrap(); + assert!( + sv.contains_key(&high_id), + "53-bit clientId must not be truncated to u32" + ); +} + +#[test] +fn all_phase1_blocks_surface_elements_and_unknown_block_lossless() { + let mut ws = WorkspaceSession::new("room-schema", client_id_from_seed(1)).unwrap(); + ws.initialize_meta().unwrap(); + ws.create_page("doc:home", "Native Schema Doc", 1_700_000_000_000) + .unwrap(); + + let page = ws.page_mut("doc:home").unwrap(); + page.add_block( + "page-1", + BlockSpec::Page { + title: "Native Schema Doc".to_string(), + }, + None, + None, + 10, + ) + .unwrap(); + page.add_block("surface-1", BlockSpec::Surface, Some("page-1"), None, 20) + .unwrap(); + page.add_block( + "note-1", + BlockSpec::Note { + xywh: Some("[0,100,800,640]".to_string()), + }, + Some("page-1"), + None, + 30, + ) + .unwrap(); + page.add_block( + "p-1", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::H1, + text: "Heading".to_string(), + }, + Some("note-1"), + None, + 40, + ) + .unwrap(); + page.add_block( + "l-1", + BlockSpec::List { + list_type: ListType::Todo, + text: "Task".to_string(), + checked: true, + order: None, + }, + Some("note-1"), + None, + 50, + ) + .unwrap(); + page.add_block("d-1", BlockSpec::Divider, Some("note-1"), None, 60) + .unwrap(); + page.add_block( + "c-1", + BlockSpec::Code { + text: "fn main() {}".to_string(), + language: Some("rust".to_string()), + caption: "sample".to_string(), + }, + Some("note-1"), + None, + 70, + ) + .unwrap(); + page.add_block( + "img-1", + BlockSpec::Image { + source_id: "blob-1".to_string(), + caption: "pic".to_string(), + width: 320.0, + height: 240.0, + xywh: Some("[0,0,320,240]".to_string()), + }, + Some("note-1"), + None, + 80, + ) + .unwrap(); + page.add_block( + "bm-1", + BlockSpec::Bookmark { + url: "https://affine.pro".to_string(), + title: Some("AFFiNE".to_string()), + description: Some("Workspace".to_string()), + }, + Some("note-1"), + None, + 90, + ) + .unwrap(); + page.add_block( + "frame-1", + BlockSpec::Frame { + title: "Frame A".to_string(), + xywh: Some("[0,0,400,300]".to_string()), + presentation_index: Some("a0".to_string()), + }, + Some("surface-1"), + None, + 100, + ) + .unwrap(); + page.add_block( + "et-1", + BlockSpec::EdgelessText { + xywh: Some("[10,20,200,40]".to_string()), + }, + Some("surface-1"), + None, + 110, + ) + .unwrap(); + + // All 6 surface elements + page.add_surface_element( + "surface-1", + "el-shape", + "a0", + SurfaceElementSpec::Shape { + shape_type: "rect".to_string(), + xywh: "[10,10,120,80]".to_string(), + seed: 42, + filled: true, + text: Some("Box".to_string()), + }, + 120, + ) + .unwrap(); + page.add_surface_element( + "surface-1", + "el-conn", + "a1", + SurfaceElementSpec::Connector { + mode: 2, + seed: 43, + source: ConnectorEndpointSpec::element("el-shape", Some([1.0, 0.5])), + target: ConnectorEndpointSpec::point(300.0, 120.0), + text: None, + label_xywh: None, + }, + 130, + ) + .unwrap(); + page.add_surface_element( + "surface-1", + "el-brush", + "a2", + SurfaceElementSpec::Brush { + seed: 44, + points: vec![vec![0.0, 0.0], vec![20.0, 15.0]], + xywh: "[0,0,24,19]".to_string(), + }, + 140, + ) + .unwrap(); + page.add_surface_element( + "surface-1", + "el-hl", + "a3", + SurfaceElementSpec::Highlighter { + seed: 45, + points: vec![vec![0.0, 0.0], vec![30.0, 10.0]], + xywh: "[0,0,52,32]".to_string(), + }, + 150, + ) + .unwrap(); + page.add_surface_element( + "surface-1", + "el-text", + "a4", + SurfaceElementSpec::Text { + seed: 46, + text: "Canvas text".to_string(), + xywh: "[50,50,120,24]".to_string(), + }, + 160, + ) + .unwrap(); + page.add_surface_element( + "surface-1", + "el-group", + "a5", + SurfaceElementSpec::Group { + seed: 47, + title: "Group 1".to_string(), + children: vec!["el-shape".to_string()], + }, + 170, + ) + .unwrap(); + + // Inject an unknown/complex block (affine:callout) and verify lossless preservation + let blocks_target = y_octo::TypeTarget::Path(y_octo::TypePath::root("blocks")); + page.inner_mut() + .map_set( + &blocks_target, + "callout-1".to_string(), + SessionValue::Map(vec![ + ( + "sys:id".to_string(), + SessionValue::Any(Any::String("callout-1".to_string())), + ), + ( + "sys:flavour".to_string(), + SessionValue::Any(Any::String("affine:callout".to_string())), + ), + ( + "sys:version".to_string(), + SessionValue::Any(Any::Integer(1)), + ), + ("sys:children".to_string(), SessionValue::Array(vec![])), + ( + "prop:emoji".to_string(), + SessionValue::Any(Any::String("💡".to_string())), + ), + ]), + ) + .unwrap(); + + let unknown = page.read_unknown_block("callout-1").unwrap(); + assert_eq!(unknown.flavour, "affine:callout"); + assert_eq!(unknown.version, Some(1)); + assert_eq!(unknown.prop_keys, vec!["prop:emoji".to_string()]); + + let exported = page.export_doc_json().unwrap(); + let blocks = exported["blocks"].as_object().unwrap(); + assert_eq!(blocks.len(), 12); + assert!( + blocks["surface-1"]["prop:elements"]["value"]["el-conn"] + .get("labelXYWH") + .is_none() + ); +} + +#[test] +fn undo_scoped_to_blocks_with_deterministic_clock_and_selection_snapshot() { + let mut page = PageDocSession::new("doc:undo", (1u64 << 35) + 7).unwrap(); + page.add_block( + "p1", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: "hello".to_string(), + }, + None, + None, + 0, + ) + .unwrap(); + page.stop_capturing().unwrap(); + + // Two edits within 500ms merge into one undo step + page.insert_text("p1", "prop:text", 5, " world", 1000) + .unwrap(); + let snap = page.capture_selection_snapshot("p1", 11, "p1", 11).unwrap(); + page.set_undo_selection_snapshot(snap.clone()).unwrap(); + page.insert_text("p1", "prop:text", 11, "!", 1200).unwrap(); + + // Third edit after >= 500ms starts a new undo step + page.insert_text("p1", "prop:text", 12, "?", 2000).unwrap(); + + assert!(page.can_undo()); + let u1 = page.undo().unwrap().expect("undo 1"); + assert_eq!(u1.selection_meta, None); + + let u2 = page.undo().unwrap().expect("undo 2"); + assert_eq!(u2.selection_meta, Some(snap)); + + let json = page.export_doc_json().unwrap(); + assert_eq!(json["blocks"]["p1"]["prop:text"][0]["insert"], "hello"); +} + +#[test] +fn add_block_invalid_parent_leaves_no_orphan_or_undo_entry() { + let mut page = PageDocSession::new("doc:invalid-parent", (1u64 << 36) + 3).unwrap(); + let sv_before = page.encode_state_vector_v1().unwrap(); + + let err = page + .add_block( + "orphan-1", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: "should not exist".to_string(), + }, + Some("nonexistent-parent"), + None, + 100, + ) + .unwrap_err(); + assert!( + matches!(err, blocksuite_playground_doc::DocError::BlockNotFound(ref id) if id == "nonexistent-parent") + ); + assert!( + !page.can_undo(), + "failed add_block must not push to Undo stack" + ); + assert_eq!( + page.encode_state_vector_v1().unwrap(), + sv_before, + "failed add_block must emit 0 commits" + ); + let exported = page.export_doc_json().unwrap(); + assert!( + exported["blocks"].as_object().unwrap().is_empty(), + "failed add_block must not leave an orphan block in blocks map" + ); +} + +#[test] +fn awareness_deterministic_clock_renew_and_expire() { + let local_id = (1u64 << 42) + 1; + let remote_id = (1u64 << 42) + 2; + + let mut local = RoomAwareness::new(local_id).unwrap(); + let mut remote = RoomAwareness::new(remote_id).unwrap(); + + // Missing color must be rejected + assert!( + local + .set_local_payload(&AwarenessPayload::new("A", ""), 0) + .is_err() + ); + + let mut payload_a = AwarenessPayload::new("Alice", "#ff5500"); + payload_a.set_selection( + "doc:home", + vec![serde_json::json!({ "type": "text", "blockId": "p1" })], + ); + let bytes_a = local.set_local_payload(&payload_a, 1_000).unwrap(); + + let payload_b = AwarenessPayload::new("Bob", "#0088ff"); + let bytes_b = remote.set_local_payload(&payload_b, 1_000).unwrap(); + + local.apply_update(&bytes_b, 1_000).unwrap(); + remote.apply_update(&bytes_a, 1_000).unwrap(); + + assert_eq!(local.get_payload(remote_id).unwrap().color, "#0088ff"); + assert_eq!(remote.get_payload(local_id).unwrap().color, "#ff5500"); + + // At +15s: local renews, remote not yet expired + let t1 = local.tick(1_000 + AWARENESS_RENEW_INTERVAL_MS).unwrap(); + assert!(t1.renewed_local); + assert!(t1.expired_clients.is_empty()); + assert!(t1.outbound_update.is_some()); + + // At +30s: remote expires + let t2 = local.tick(1_000 + AWARENESS_EXPIRE_TIMEOUT_MS).unwrap(); + assert_eq!(t2.expired_clients, vec![remote_id]); + assert!(local.get_payload(remote_id).is_none()); +} + +proptest! { + #[test] + fn wire_binary_doc_frame_roundtrip( + doc_id in "[a-zA-Z0-9:_-]{1,32}", + step in 0u8..3, + payload in proptest::collection::vec(any::(), 0..64), + ) { + let message = match step { + 0 => DocMessage::Step1(payload), + 1 => DocMessage::Step2(payload), + _ => DocMessage::Update(payload), + }; + let frame = RoomBinaryFrame::Doc { doc_id, message }; + let encoded = encode_binary_frame(&frame).unwrap(); + let decoded = decode_binary_frame(&encoded).unwrap(); + prop_assert_eq!(decoded, frame); + } +} + +#[tokio::test] +async fn room_hub_handshake_seed_cas_blobs_awareness_refcount_and_1000_step_fuzz() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr: SocketAddr = listener.local_addr().unwrap(); + let hub = RoomHub::new(); + let server = tokio::spawn(async move { + axum::serve(listener, hub.router()).await.unwrap(); + }); + + // 1. Healthz + Blob HTTP PUT/GET/DELETE + let http = reqwest::Client::new(); + let health = http + .get(format!("http://{addr}/healthz")) + .send() + .await + .unwrap(); + assert!(health.status().is_success()); + + let blob_url = format!("http://{addr}/api/collection/room-fuzz/blob/img-42"); + assert_eq!(http.get(&blob_url).send().await.unwrap().status(), 404); + assert!( + http.put(&blob_url) + .header("content-type", "application/octet-stream") + .body(vec![1u8, 2, 3, 4, 5]) + .send() + .await + .unwrap() + .status() + .is_success() + ); + let fetched = http + .get(&blob_url) + .send() + .await + .unwrap() + .bytes() + .await + .unwrap(); + assert_eq!(&fetched[..], &[1u8, 2, 3, 4, 5]); + assert!( + http.delete(&blob_url) + .send() + .await + .unwrap() + .status() + .is_success() + ); + assert_eq!(http.get(&blob_url).send().await.unwrap().status(), 404); + + // Verify >2 MiB image blob roundtrip (exceeds Axum's default 2 MiB body limit) + let large_blob = vec![0xABu8; 3 * 1024 * 1024]; + let large_url = format!("http://{addr}/api/collection/room-fuzz/blob/img-3mib"); + assert!( + http.put(&large_url) + .header("content-type", "application/octet-stream") + .body(large_blob.clone()) + .send() + .await + .unwrap() + .status() + .is_success() + ); + let fetched_large = http + .get(&large_url) + .send() + .await + .unwrap() + .bytes() + .await + .unwrap(); + assert_eq!(fetched_large.len(), large_blob.len()); + assert_eq!(&fetched_large[..], &large_blob[..]); + assert!( + http.delete(&large_url) + .send() + .await + .unwrap() + .status() + .is_success() + ); + + // 2. Seed-claim single-winner CAS + Awareness multi-connection refcount + let ws_url = format!("ws://{addr}/native-sync/rooms/room-fuzz"); + let (mut ws1, _) = connect_async(&ws_url).await.unwrap(); + let (mut ws2, _) = connect_async(&ws_url).await.unwrap(); + let (mut ws3, _) = connect_async(&ws_url).await.unwrap(); + + let claim = encode_control_frame(&RoomControlFrame::SeedClaim { + key: "init".to_string(), + }) + .unwrap(); + ws1.send(WsMsg::Text(claim.clone().into())).await.unwrap(); + let r1 = match ws1.next().await.unwrap().unwrap() { + WsMsg::Text(t) => decode_control_frame(&t).unwrap(), + other => panic!("unexpected: {other:?}"), + }; + assert_eq!( + r1, + RoomControlFrame::SeedClaimResult { + key: "init".to_string(), + winner: true + } + ); + + ws2.send(WsMsg::Text(claim.into())).await.unwrap(); + let r2 = match ws2.next().await.unwrap().unwrap() { + WsMsg::Text(t) => decode_control_frame(&t).unwrap(), + other => panic!("unexpected: {other:?}"), + }; + assert_eq!( + r2, + RoomControlFrame::SeedClaimResult { + key: "init".to_string(), + winner: false + } + ); + + // Same client_id announced on ws1 AND ws2; observer on ws3 + let shared_cid = (1u64 << 45) + 99; + let mut aw_sender = RoomAwareness::new(shared_cid).unwrap(); + let aw_bytes = aw_sender + .set_local_payload(&AwarenessPayload::new("DualConn", "#12aa34"), 0) + .unwrap(); + let aw_frame = encode_binary_frame(&RoomBinaryFrame::Awareness(aw_bytes)).unwrap(); + ws1.send(WsMsg::Binary(aw_frame.clone().into())) + .await + .unwrap(); + ws2.send(WsMsg::Binary(aw_frame.into())).await.unwrap(); + + let mut aw_observer = RoomAwareness::new((1u64 << 45) + 100).unwrap(); + if let Some(Ok(WsMsg::Binary(b))) = ws3.next().await + && let RoomBinaryFrame::Awareness(payload) = decode_binary_frame(&b).unwrap() + { + aw_observer.apply_update(&payload, 10).unwrap(); + } + assert!(aw_observer.get_payload(shared_cid).is_some()); + + // Closing ws1 must NOT mark shared_cid offline because ws2 still holds it. + ws1.close(None).await.unwrap(); + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + // Closing ws2 MUST broadcast offline removal to ws3. + ws2.close(None).await.unwrap(); + let offline_msg = tokio::time::timeout(std::time::Duration::from_secs(2), ws3.next()) + .await + .expect("expected offline broadcast") + .unwrap() + .unwrap(); + if let WsMsg::Binary(b) = offline_msg + && let RoomBinaryFrame::Awareness(payload) = decode_binary_frame(&b).unwrap() + { + aw_observer.apply_update(&payload, 20).unwrap(); + } + assert!(aw_observer.get_payload(shared_cid).is_none()); + ws3.close(None).await.unwrap(); + + // 3. 1,000-step deterministic seeded concurrent fuzz between two WorkspaceSessions over RoomHub + let mut peer_a = WorkspaceSession::new("room-fuzz", (1u64 << 40) + 1).unwrap(); + let mut peer_b = WorkspaceSession::new("room-fuzz", (1u64 << 40) + 2).unwrap(); + peer_a.initialize_meta().unwrap(); + peer_a.create_page("doc:home", "Fuzz", 1).unwrap(); + peer_b.ensure_page("doc:home").unwrap(); + + // Seed initial structure on peer_a + { + let p = peer_a.page_mut("doc:home").unwrap(); + p.add_block( + "root", + BlockSpec::Page { + title: "Fuzz".to_string(), + }, + None, + None, + 0, + ) + .unwrap(); + p.add_block("surface", BlockSpec::Surface, Some("root"), None, 1) + .unwrap(); + p.add_block( + "note", + BlockSpec::Note { xywh: None }, + Some("root"), + None, + 2, + ) + .unwrap(); + for i in 0..4 { + p.add_block( + format!("p{i}"), + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: format!("seed-{i}"), + }, + Some("note"), + None, + 3 + i, + ) + .unwrap(); + } + p.add_surface_element( + "surface", + "shape-1", + "a0", + SurfaceElementSpec::Shape { + shape_type: "rect".to_string(), + xywh: "[0,0,100,100]".to_string(), + seed: 7, + filled: false, + text: None, + }, + 10, + ) + .unwrap(); + } + + async fn sync_doc( + ws: &mut tokio_tungstenite::WebSocketStream< + tokio_tungstenite::MaybeTlsStream, + >, + page: &mut PageDocSession, + doc_id: &str, + ) { + let mut state = DocSyncState::new(doc_id); + let step1 = state.begin_pull(page.encode_state_vector_v1().unwrap()); + ws.send(WsMsg::Binary(encode_binary_frame(&step1).unwrap().into())) + .await + .unwrap(); + let hub_sv = loop { + if let WsMsg::Binary(b) = ws.next().await.unwrap().unwrap() { + match decode_binary_frame(&b).unwrap() { + RoomBinaryFrame::Doc { + doc_id: d, + message: DocMessage::Step2(diff), + } if d == doc_id => { + if !(diff.is_empty() || diff == [0, 0]) { + page.apply_remote_update_v1(&diff).unwrap(); + } + if let Some(sv) = state.on_hub_step2() { + break sv; + } + } + RoomBinaryFrame::Doc { + doc_id: d, + message: DocMessage::Step1(sv), + } if d == doc_id => { + if let Some(sv) = state.on_hub_step1(sv) { + break sv; + } + } + _ => {} + } + } + }; + assert_eq!(state.phase(), DocSyncPhase::Synced); + let diff_to_hub = page.encode_diff_v1(&hub_sv).unwrap(); + let rev_step2 = state.build_reverse_step2(diff_to_hub); + ws.send(WsMsg::Binary( + encode_binary_frame(&rev_step2).unwrap().into(), + )) + .await + .unwrap(); + // Wait for hub Ready control frame + loop { + if let WsMsg::Text(t) = ws.next().await.unwrap().unwrap() + && let Ok(RoomControlFrame::Ready { doc_id: d }) = decode_control_frame(&t) + && d == doc_id + { + break; + } + } + } + + let (mut sock_a, _) = connect_async(&ws_url).await.unwrap(); + let (mut sock_b, _) = connect_async(&ws_url).await.unwrap(); + sync_doc( + &mut sock_a, + peer_a.page_mut("doc:home").unwrap(), + "doc:home", + ) + .await; + sync_doc( + &mut sock_b, + peer_b.page_mut("doc:home").unwrap(), + "doc:home", + ) + .await; + + let mut rng = ChaCha8Rng::seed_from_u64(0xB5_2026_1000); + for step in 0..1_000u64 { + let on_a = rng.random_bool(0.5); + let page = if on_a { + peer_a.page_mut("doc:home").unwrap() + } else { + peer_b.page_mut("doc:home").unwrap() + }; + let target_block = format!("p{}", rng.random_range(0..4)); + let now_ms = 1_000 + step * 10; + + let commit = match rng.random_range(0..5u8) { + 0 => { + let target = y_octo::TypeTarget::Path( + y_octo::TypePath::root("blocks") + .key(&target_block) + .key("prop:text"), + ); + let len = page.inner().read_text_len(&target).unwrap_or(0); + let idx = if len == 0 { + 0 + } else { + rng.random_range(0..=len) + }; + let ch = format!("{}", (b'a' + (step % 26) as u8) as char); + page.insert_text(&target_block, "prop:text", idx, &ch, now_ms) + .unwrap() + } + 1 => { + let target = y_octo::TypeTarget::Path( + y_octo::TypePath::root("blocks") + .key(&target_block) + .key("prop:text"), + ); + let len = page.inner().read_text_len(&target).unwrap_or(0); + if len > 0 { + let idx = rng.random_range(0..len); + let del = rng.random_range(1..=(len - idx).min(3)); + page.remove_text(&target_block, "prop:text", idx, del, now_ms) + .unwrap() + } else { + None + } + } + 2 => { + let target = y_octo::TypeTarget::Path( + y_octo::TypePath::root("blocks") + .key(&target_block) + .key("prop:text"), + ); + let len = page.inner().read_text_len(&target).unwrap_or(0); + if len > 0 { + let idx = rng.random_range(0..len); + let fmt_len = rng.random_range(1..=(len - idx).min(4)); + let mut attrs = TextAttributes::new(); + attrs.insert("bold".to_string(), Any::True); + page.format_text(&target_block, "prop:text", idx, fmt_len, attrs, now_ms) + .unwrap() + } else { + None + } + } + 3 => { + let new_idx = rng.random_range(0..4); + page.reorder_child("note", &target_block, new_idx, now_ms) + .unwrap() + } + _ => { + let x = rng.random_range(0..500); + let y = rng.random_range(0..500); + page.set_surface_element_field( + "surface", + "shape-1", + "xywh", + SessionValue::Any(Any::String(format!("[{x},{y},100,100]"))), + now_ms, + ) + .unwrap() + } + }; + + if let Some(c) = commit + && !c.update.is_empty() + { + let frame = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id: "doc:home".to_string(), + message: DocMessage::Update(c.update), + }) + .unwrap(); + if on_a { + sock_a.send(WsMsg::Binary(frame.into())).await.unwrap(); + } else { + sock_b.send(WsMsg::Binary(frame.into())).await.unwrap(); + } + } + + // Simulate mid-flight disconnect & reconnect at step 500 + if step == 500 { + sock_b.close(None).await.unwrap(); + let (reconn, _) = connect_async(&ws_url).await.unwrap(); + sock_b = reconn; + sync_doc( + &mut sock_b, + peer_b.page_mut("doc:home").unwrap(), + "doc:home", + ) + .await; + } + } + + // Drain any in-flight messages and perform final bidirectional resync + sock_a.close(None).await.unwrap(); + sock_b.close(None).await.unwrap(); + let (mut final_a, _) = connect_async(&ws_url).await.unwrap(); + let (mut final_b, _) = connect_async(&ws_url).await.unwrap(); + sync_doc( + &mut final_a, + peer_a.page_mut("doc:home").unwrap(), + "doc:home", + ) + .await; + sync_doc( + &mut final_b, + peer_b.page_mut("doc:home").unwrap(), + "doc:home", + ) + .await; + sync_doc( + &mut final_a, + peer_a.page_mut("doc:home").unwrap(), + "doc:home", + ) + .await; + + let sv_a = peer_a + .page("doc:home") + .unwrap() + .encode_state_vector_v1() + .unwrap(); + let sv_b = peer_b + .page("doc:home") + .unwrap() + .encode_state_vector_v1() + .unwrap(); + assert_eq!( + StateVector::decode_v1(&sv_a).unwrap(), + StateVector::decode_v1(&sv_b).unwrap(), + "StateVectors must match after 1,000-step concurrent fuzz" + ); + + let json_a = peer_a.page("doc:home").unwrap().export_doc_json().unwrap(); + let json_b = peer_b.page("doc:home").unwrap().export_doc_json().unwrap(); + assert_eq!( + json_a, json_b, + "Normalized doc.json must match after 1,000-step fuzz" + ); + + let diff_ab = peer_a + .page("doc:home") + .unwrap() + .encode_diff_v1(&sv_b) + .unwrap(); + let diff_ba = peer_b + .page("doc:home") + .unwrap() + .encode_diff_v1(&sv_a) + .unwrap(); + assert!( + peer_b + .page_mut("doc:home") + .unwrap() + .apply_remote_update_v1(&diff_ab) + .unwrap() + .commits + .is_empty(), + "Applying diff_ab to converged peer_b must produce 0 commits" + ); + assert!( + peer_a + .page_mut("doc:home") + .unwrap() + .apply_remote_update_v1(&diff_ba) + .unwrap() + .commits + .is_empty(), + "Applying diff_ba to converged peer_a must produce 0 commits" + ); + + final_a.close(None).await.unwrap(); + final_b.close(None).await.unwrap(); + server.abort(); +} + +#[tokio::test] +async fn room_hub_awareness_equal_clock_refcount_seed_promotion_and_blob_cors() { + let hub = RoomHub::new(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + axum::serve(listener, hub.router()).await.unwrap(); + }); + + // 1. Blob CORS preflight (OPTIONS -> 204) and CORS headers on PUT/GET/DELETE. + let http = reqwest::Client::new(); + let blob_url = format!("http://{addr}/api/collection/cors-room/blob/img-1"); + let preflight = http + .request(reqwest::Method::OPTIONS, &blob_url) + .send() + .await + .unwrap(); + assert_eq!(preflight.status(), reqwest::StatusCode::NO_CONTENT); + assert_eq!( + preflight + .headers() + .get("access-control-allow-origin") + .and_then(|v| v.to_str().ok()), + Some("*") + ); + assert!( + preflight + .headers() + .get("access-control-allow-methods") + .and_then(|v| v.to_str().ok()) + .is_some_and(|m| m.contains("PUT") && m.contains("OPTIONS")) + ); + assert_eq!( + preflight + .headers() + .get("access-control-allow-headers") + .and_then(|v| v.to_str().ok()), + Some("Content-Type") + ); + + let put_resp = http + .put(&blob_url) + .header("content-type", "application/octet-stream") + .body(vec![7u8, 8, 9]) + .send() + .await + .unwrap(); + assert!(put_resp.status().is_success()); + assert_eq!( + put_resp + .headers() + .get("access-control-allow-origin") + .and_then(|v| v.to_str().ok()), + Some("*") + ); + + let get_resp = http.get(&blob_url).send().await.unwrap(); + assert!(get_resp.status().is_success()); + assert_eq!( + get_resp + .headers() + .get("access-control-allow-origin") + .and_then(|v| v.to_str().ok()), + Some("*") + ); + assert_eq!(get_resp.bytes().await.unwrap().as_ref(), &[7u8, 8, 9]); + + // 2. Equal-clock awareness announcement across two connections -> closing conn1 must keep + // conn2's state live for a fresh observer. + let ws_url = format!("ws://{addr}/native-sync/rooms/room-hardening"); + let (mut conn1, _) = connect_async(&ws_url).await.unwrap(); + let (mut conn2, _) = connect_async(&ws_url).await.unwrap(); + + let shared_cid = (1u64 << 46) + 77; + let mut aw_sender = RoomAwareness::new(shared_cid).unwrap(); + let live_bytes = aw_sender + .set_local_payload(&AwarenessPayload::new("SameClockPeer", "#3366ff"), 0) + .unwrap(); + let live_frame = encode_binary_frame(&RoomBinaryFrame::Awareness(live_bytes)).unwrap(); + + // Both connections send the EXACT same (client_id, clock) frame. + conn1 + .send(WsMsg::Binary(live_frame.clone().into())) + .await + .unwrap(); + conn2.send(WsMsg::Binary(live_frame.into())).await.unwrap(); + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + + // Close conn1; conn2 still owns shared_cid so a fresh observer MUST see it live. + conn1.close(None).await.unwrap(); + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + + let (mut fresh_obs, _) = connect_async(&ws_url).await.unwrap(); + let initial_aw = tokio::time::timeout(std::time::Duration::from_secs(2), fresh_obs.next()) + .await + .expect("fresh observer should receive live awareness snapshot") + .unwrap() + .unwrap(); + let mut obs_awareness = RoomAwareness::new((1u64 << 46) + 78).unwrap(); + if let WsMsg::Binary(b) = initial_aw + && let RoomBinaryFrame::Awareness(payload) = decode_binary_frame(&b).unwrap() + { + obs_awareness.apply_update(&payload, 10).unwrap(); + } + assert_eq!( + obs_awareness.get_payload(shared_cid).map(|p| p.user.name), + Some("SameClockPeer".to_string()) + ); + + // Closing conn2 finally tombstones shared_cid and notifies fresh_obs. + conn2.close(None).await.unwrap(); + let offline_aw = tokio::time::timeout(std::time::Duration::from_secs(2), fresh_obs.next()) + .await + .expect("expected offline broadcast after last owner disconnects") + .unwrap() + .unwrap(); + if let WsMsg::Binary(b) = offline_aw + && let RoomBinaryFrame::Awareness(payload) = decode_binary_frame(&b).unwrap() + { + obs_awareness.apply_update(&payload, 20).unwrap(); + } + assert!(obs_awareness.get_payload(shared_cid).is_none()); + fresh_obs.close(None).await.unwrap(); + + // 3. Seed CAS FIFO waiter promotion on partial-seed disconnect. + let seed_ws_url = format!("ws://{addr}/native-sync/rooms/room-seed-promote"); + let (mut s1, _) = connect_async(&seed_ws_url).await.unwrap(); + let (mut s2, _) = connect_async(&seed_ws_url).await.unwrap(); + + let claim = encode_control_frame(&RoomControlFrame::SeedClaim { + key: "seed:doc:home".to_string(), + }) + .unwrap(); + s1.send(WsMsg::Text(claim.clone().into())).await.unwrap(); + let r1 = match s1.next().await.unwrap().unwrap() { + WsMsg::Text(t) => decode_control_frame(&t).unwrap(), + other => panic!("unexpected: {other:?}"), + }; + assert_eq!( + r1, + RoomControlFrame::SeedClaimResult { + key: "seed:doc:home".to_string(), + winner: true + } + ); + + // s2 claims while s1 is pending -> s2 is queued (no immediate reply). + s2.send(WsMsg::Text(claim.clone().into())).await.unwrap(); + assert!( + tokio::time::timeout(std::time::Duration::from_millis(80), s2.next()) + .await + .is_err(), + "waiter should stay queued while winner is still connected and seeding" + ); + + // s1 disconnects WITHOUT seeding doc:home -> s2 must be promoted to winner=true! + s1.close(None).await.unwrap(); + let r2 = tokio::time::timeout(std::time::Duration::from_secs(2), s2.next()) + .await + .expect("waiter should be promoted on winner disconnect") + .unwrap() + .unwrap(); + let r2 = match r2 { + WsMsg::Text(t) => decode_control_frame(&t).unwrap(), + other => panic!("unexpected: {other:?}"), + }; + assert_eq!( + r2, + RoomControlFrame::SeedClaimResult { + key: "seed:doc:home".to_string(), + winner: true + } + ); + + // s2 seeds doc:home with a usable affine:page root -> subsequent claimer s3 gets winner=false. + let mut page = PageDocSession::new("doc:home", (1u64 << 46) + 90).unwrap(); + page.add_block( + "root", + BlockSpec::Page { + title: "Promoted".to_string(), + }, + None, + None, + 1, + ) + .unwrap(); + let update = page.encode_update_v1().unwrap(); + let doc_frame = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id: "doc:home".to_string(), + message: DocMessage::Update(update), + }) + .unwrap(); + s2.send(WsMsg::Binary(doc_frame.into())).await.unwrap(); + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + + let (mut s3, _) = connect_async(&seed_ws_url).await.unwrap(); + s3.send(WsMsg::Text(claim.into())).await.unwrap(); + let r3 = match s3.next().await.unwrap().unwrap() { + WsMsg::Text(t) => decode_control_frame(&t).unwrap(), + other => panic!("unexpected: {other:?}"), + }; + assert_eq!( + r3, + RoomControlFrame::SeedClaimResult { + key: "seed:doc:home".to_string(), + winner: false + } + ); + + s2.close(None).await.unwrap(); + s3.close(None).await.unwrap(); + server.abort(); +} diff --git a/blocksuite/native-playground/crates/playground/Cargo.toml b/blocksuite/native-playground/crates/playground/Cargo.toml index 43ea540e98..3106dc7b03 100644 --- a/blocksuite/native-playground/crates/playground/Cargo.toml +++ b/blocksuite/native-playground/crates/playground/Cargo.toml @@ -26,6 +26,7 @@ required-features = ["harness"] [dependencies] anyhow.workspace = true +blocksuite-playground-doc = { path = "../doc", default-features = false } image.workspace = true serde.workspace = true serde_json.workspace = true diff --git a/blocksuite/native-playground/crates/playground/src/bin/bs_harness.rs b/blocksuite/native-playground/crates/playground/src/bin/bs_harness.rs index 2f406afa83..1915f1baba 100644 --- a/blocksuite/native-playground/crates/playground/src/bin/bs_harness.rs +++ b/blocksuite/native-playground/crates/playground/src/bin/bs_harness.rs @@ -1,4 +1,10 @@ use anyhow::{Context as _, Result, bail}; +use blocksuite_playground_doc::{ + client_id_from_seed, + schema::{BlockSpec, ParagraphType}, + session::PageDocSession, + wire::{DocMessage, RoomBinaryFrame, decode_binary_frame, encode_binary_frame}, +}; use playground::{PlaygroundView, register_bundled_fonts}; use serde::Serialize; use std::cell::RefCell; @@ -396,6 +402,169 @@ fn timing_stat(mut samples_ms: Vec) -> TimingStat { } } +fn run_doc_1k_edits_once(seed: u64) -> Result<()> { + let mut doc = PageDocSession::new("bench-page", client_id_from_seed(seed))?; + doc.add_block( + "page-root", + BlockSpec::Page { + title: "Bench Page".to_string(), + }, + None, + None, + 1_000, + )?; + doc.add_block( + "note-root", + BlockSpec::Note { xywh: None }, + Some("page-root"), + None, + 1_001, + )?; + doc.add_block( + "p-main", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: String::new(), + }, + Some("note-root"), + None, + 1_002, + )?; + + let mut now_ms = 2_000_u64; + // 100 block additions + for i in 0..100_u64 { + doc.add_block( + format!("p-{i}"), + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: format!("block {i}"), + }, + Some("note-root"), + None, + now_ms, + )?; + now_ms += 600; + } + + // 700 text insertions into p-main + let mut text_len = 0_u64; + for i in 0..700_u64 { + let ch = if i % 2 == 0 { "a" } else { "b" }; + doc.insert_text("p-main", "prop:text", text_len, ch, now_ms)?; + text_len += 1; + now_ms += 600; + } + + // 100 text removals + for _ in 0..100_u64 { + text_len -= 1; + doc.remove_text("p-main", "prop:text", text_len, 1, now_ms)?; + now_ms += 600; + } + + // 50 undos + 50 redos + for _ in 0..50_u64 { + doc.undo()?; + } + for _ in 0..50_u64 { + doc.redo()?; + } + + Ok(()) +} + +fn bench_doc_1k_edits_ms() -> Result { + // 1 warmup iteration outside timing loop + run_doc_1k_edits_once(0)?; + + let mut samples_ms = Vec::with_capacity(20); + for sample in 1..=20_u64 { + let start = ui::clock_now(); + run_doc_1k_edits_once(sample)?; + samples_ms.push(start.elapsed().as_secs_f64() * 1000.0); + } + Ok(timing_stat(samples_ms)) +} + +fn run_room_sync_1k_ops_once(seed: u64) -> Result<()> { + let mut peer_a = PageDocSession::new("bench-sync", client_id_from_seed(seed * 2 + 1))?; + let mut peer_b = PageDocSession::new("bench-sync", client_id_from_seed(seed * 2 + 2))?; + + peer_a.add_block( + "page-root", + BlockSpec::Page { + title: "Sync Bench".to_string(), + }, + None, + None, + 1_000, + )?; + peer_a.add_block( + "note-root", + BlockSpec::Note { xywh: None }, + Some("page-root"), + None, + 1_001, + )?; + peer_a.add_block( + "p-sync", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: String::new(), + }, + Some("note-root"), + None, + 1_002, + )?; + + let init_update = peer_a.encode_update_v1()?; + peer_b.apply_remote_update_v1(&init_update)?; + + let mut now_ms = 2_000_u64; + for i in 0..1_000_u64 { + let commit = peer_a + .insert_text( + "p-sync", + "prop:text", + i, + if i % 2 == 0 { "x" } else { "y" }, + now_ms, + )? + .context("insert_text should emit a commit")?; + now_ms += 10; + + let encoded = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id: "bench-sync".to_string(), + message: DocMessage::Update(commit.update), + })?; + match decode_binary_frame(&encoded)? { + RoomBinaryFrame::Doc { + message: DocMessage::Update(update), + .. + } => { + peer_b.apply_remote_update_v1(&update)?; + } + other => bail!("unexpected decoded room frame: {other:?}"), + } + } + + Ok(()) +} + +fn bench_room_sync_1k_ops_ms() -> Result { + // 1 warmup iteration outside timing loop + run_room_sync_1k_ops_once(0)?; + + let mut samples_ms = Vec::with_capacity(20); + for sample in 1..=20_u64 { + let start = ui::clock_now(); + run_room_sync_1k_ops_once(sample)?; + samples_ms.push(start.elapsed().as_secs_f64() * 1000.0); + } + Ok(timing_stat(samples_ms)) +} + fn run_bench( out_json: PathBuf, explicit_commit: Option, @@ -403,6 +572,8 @@ fn run_bench( web_wasm_gzip: Option, ) -> Result<()> { let commit = resolve_commit_sha(explicit_commit.as_deref())?; + let doc_1k_edits_ms = bench_doc_1k_edits_ms()?; + let room_sync_1k_ops_ms = bench_room_sync_1k_ops_ms()?; let session = start_headless_session(1280, 800)?; // 1 warmup frame outside timing loop @@ -448,8 +619,8 @@ fn run_bench( headless_bin, }, benchmarks: BenchmarksV1 { - doc_1k_edits_ms: None, - room_sync_1k_ops_ms: None, + doc_1k_edits_ms: Some(doc_1k_edits_ms), + room_sync_1k_ops_ms: Some(room_sync_1k_ops_ms), layout_10k_blocks_cold_ms: None, layout_single_keystroke_ms: None, layout_single_keystroke_blocks_relayout: None, diff --git a/blocksuite/native-playground/scripts/check-invariants.sh b/blocksuite/native-playground/scripts/check-invariants.sh index 69bf8e43f8..f124829a9e 100755 --- a/blocksuite/native-playground/scripts/check-invariants.sh +++ b/blocksuite/native-playground/scripts/check-invariants.sh @@ -21,6 +21,14 @@ if grep -rniE '\b(blocksuite|affine)\b' crates/ui/src crates/ui/Cargo.toml 2>/de fail "crates/ui must not reference BlockSuite or AFFiNE domain terms" fi +echo "==> Checking crates/doc GUI isolation and forbid(unsafe_code)" +if grep -rnE '^\s*(ui|wgpu|objc2|web-sys)\b' crates/doc/Cargo.toml 2>/dev/null; then + fail "crates/doc must not depend on GUI/platform crates (ui, wgpu, objc2, web-sys)" +fi +if ! grep -q '#!\[forbid(unsafe_code)\]' crates/doc/src/lib.rs; then + fail "crates/doc/src/lib.rs must declare #![forbid(unsafe_code)]" +fi + echo "==> Checking no Instant::now / SystemTime::now outside crates/ui/src/platform" WALL_CLOCK_HITS=$( grep -rnE '(Instant::now|SystemTime::now)\s*\(' crates/ \ diff --git a/blocksuite/playground/apps/_common/sync/blob/mock-server.ts b/blocksuite/playground/apps/_common/sync/blob/mock-server.ts index 05590f3d74..9dace47d7a 100644 --- a/blocksuite/playground/apps/_common/sync/blob/mock-server.ts +++ b/blocksuite/playground/apps/_common/sync/blob/mock-server.ts @@ -15,15 +15,25 @@ export class MockServerBlobSource implements BlobSource { readonly = false; - constructor(readonly name: string) {} + constructor( + readonly name: string, + readonly baseUrl = '' + ) {} + + private _blobUrl(key: string) { + return `${this.baseUrl}/api/collection/${encodeURIComponent(this.name)}/blob/${encodeURIComponent(key)}`; + } async delete(key: string) { this._cache.delete(key); this._states.delete(key); - await fetch(`/api/collection/${this.name}/blob/${key}`, { + const resp = await fetch(this._blobUrl(key), { method: 'DELETE', }); + if (!resp.ok) { + throw new Error(`Failed to delete blob ${key}: ${resp.status}`); + } } async get(key: string) { @@ -41,7 +51,7 @@ export class MockServerBlobSource implements BlobSource { nextState(state$, { downloading: true }); try { - const resp = await fetch(`/api/collection/${this.name}/blob/${key}`); + const resp = await fetch(this._blobUrl(key)); if (!resp.ok) throw new Error(`Failed to fetch blob ${key}`); @@ -77,10 +87,13 @@ export class MockServerBlobSource implements BlobSource { nextState(state$, { uploading: true }); try { - await fetch(`/api/collection/${this.name}/blob/${key}`, { + const resp = await fetch(this._blobUrl(key), { method: 'PUT', body: value, }); + if (!resp.ok) { + throw new Error(`Failed to upload blob ${key}: ${resp.status}`); + } } catch (err) { const errorMessage = err instanceof Error ? err.message : String(err); nextState(state$, { errorMessage }); diff --git a/blocksuite/playground/apps/_common/sync/room/__tests__/room-sync.spec.ts b/blocksuite/playground/apps/_common/sync/room/__tests__/room-sync.spec.ts new file mode 100644 index 0000000000..0cfe8a6fa0 --- /dev/null +++ b/blocksuite/playground/apps/_common/sync/room/__tests__/room-sync.spec.ts @@ -0,0 +1,1071 @@ +import { type ChildProcessWithoutNullStreams, spawn } from 'node:child_process'; +import { existsSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { createInterface } from 'node:readline'; + +import { AffineSchemas } from '@blocksuite/affine/schemas'; +import { TextSelection } from '@blocksuite/affine/std'; +import { BlockSchemaExtension, Schema, Text } from '@blocksuite/affine/store'; +import { TestWorkspace } from '@blocksuite/affine/store/test'; +import { MemoryBlobSource } from '@blocksuite/affine/sync'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import * as Y from 'yjs'; + +import { MockServerBlobSource } from '../../blob/mock-server.js'; +import { + hasUsablePageRoot, + initRoomDocWithSeed, + RoomWebSocketClient, +} from '../index.js'; + +const NATIVE_DIR = resolve(__dirname, '../../../../../../native-playground'); +const RELAY_BIN = + process.env.BS_RELAY_BIN ?? resolve(NATIVE_DIR, 'target/debug/bs-relay'); +const DRIVER_BIN = + process.env.BS_DOC_DRIVER_BIN ?? + resolve(NATIVE_DIR, 'target/debug/examples/bs_doc_driver'); + +function normalizeYValue(val: unknown): unknown { + if (val instanceof Y.Map) { + const entries = Array.from(val.entries()).sort(([a], [b]) => + a < b ? -1 : a > b ? 1 : 0 + ); + const obj: Record = {}; + for (const [k, v] of entries) { + obj[k] = normalizeYValue(v); + } + return obj; + } + if (val instanceof Y.Array) { + return val.toArray().map(item => normalizeYValue(item)); + } + if (val instanceof Y.Text) { + const delta = val.toDelta() as Array<{ + insert: unknown; + attributes?: Record; + }>; + const ops: Array> = []; + for (const op of delta) { + const insert = normalizeYValue(op.insert); + let sortedAttrs: Record | undefined; + if (op.attributes && Object.keys(op.attributes).length > 0) { + sortedAttrs = {}; + for (const k of Object.keys(op.attributes).sort()) { + sortedAttrs[k] = normalizeYValue(op.attributes[k]); + } + } + const prev = ops[ops.length - 1]; + if ( + typeof insert === 'string' && + prev && + typeof prev['insert'] === 'string' && + JSON.stringify(prev['attributes']) === JSON.stringify(sortedAttrs) + ) { + prev['insert'] = `${prev['insert']}${insert}`; + continue; + } + const out: Record = { insert }; + if (sortedAttrs) { + out['attributes'] = sortedAttrs; + } + ops.push(out); + } + return ops; + } + if (val instanceof Y.Doc) { + return val.guid; + } + if (Array.isArray(val)) { + return val.map(item => normalizeYValue(item)); + } + if (val !== null && typeof val === 'object') { + const obj: Record = {}; + for (const k of Object.keys(val as Record).sort()) { + obj[k] = normalizeYValue((val as Record)[k]); + } + return obj; + } + return val; +} + +function exportJsDocJson(doc: Y.Doc) { + return { + guid: doc.guid, + blocks: normalizeYValue(doc.getMap('blocks')), + }; +} + +function exportJsStateVector(doc: Y.Doc): Record { + const sv = Y.decodeStateVector(Y.encodeStateVector(doc)); + const out: Record = {}; + for (const [cid, clock] of Array.from(sv.entries()).sort( + ([a], [b]) => a - b + )) { + out[String(cid)] = clock; + } + return out; +} + +function exportDeleteSetFromUpdate( + fullUpdate: Uint8Array +): Record> { + const decoded = Y.decodeUpdate(fullUpdate); + const out: Record> = {}; + for (const [cid, items] of Array.from(decoded.ds.clients.entries()).sort( + ([a], [b]) => a - b + )) { + if (items.length > 0) { + out[String(cid)] = items.map(item => [item.clock, item.len]); + } + } + return out; +} + +function exportJsDeleteSet( + doc: Y.Doc +): Record> { + return exportDeleteSetFromUpdate(Y.encodeStateAsUpdate(doc)); +} + +class RustDriver { + private readonly proc: ChildProcessWithoutNullStreams; + private readonly lineQueue: string[] = []; + private readonly waiters: Array<(line: string) => void> = []; + + constructor(relayHttp: string, room: string, clientId: number) { + this.proc = spawn( + DRIVER_BIN, + [ + '--relay-http', + relayHttp, + '--room', + room, + '--client-id', + String(clientId), + ], + { stdio: ['pipe', 'pipe', 'pipe'] } + ); + const rl = createInterface({ input: this.proc.stdout }); + rl.on('line', line => { + const waiter = this.waiters.shift(); + if (waiter) { + waiter(line); + } else { + this.lineQueue.push(line); + } + }); + } + + private nextLine(): Promise { + const queued = this.lineQueue.shift(); + if (queued !== undefined) return Promise.resolve(queued); + return new Promise(resolve => this.waiters.push(resolve)); + } + + async waitReady() { + const line = await this.nextLine(); + expect(line.trim()).toBe('READY'); + } + + async call>( + cmd: Record + ): Promise { + this.proc.stdin.write(`${JSON.stringify(cmd)}\n`); + const line = await this.nextLine(); + return JSON.parse(line) as T; + } + + async quit() { + try { + await this.call({ cmd: 'quit' }); + } catch { + this.proc.kill(); + } + } +} + +function createMulberry32(seed: number) { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +describe('Rust bs-relay + WorkspaceSession <-> JS BlockSuite TestWorkspace', () => { + let relayProc: ChildProcessWithoutNullStreams; + let relayHttp = ''; + let relayWsBase = ''; + + beforeAll(async () => { + expect( + existsSync(RELAY_BIN), + `Missing ${RELAY_BIN}; build bs-relay first` + ).toBe(true); + expect( + existsSync(DRIVER_BIN), + `Missing ${DRIVER_BIN}; build bs_doc_driver example first` + ).toBe(true); + + relayProc = spawn(RELAY_BIN, ['--host', '127.0.0.1', '--port', '0'], { + stdio: ['pipe', 'pipe', 'pipe'], + }); + + const listenLine = await new Promise((resolveLine, rejectLine) => { + const rl = createInterface({ input: relayProc.stdout }); + const timer = setTimeout( + () => rejectLine(new Error('Timed out waiting for bs-relay')), + 10_000 + ); + rl.on('line', line => { + if (line.startsWith('LISTENING ')) { + clearTimeout(timer); + resolveLine(line); + } + }); + }); + + const addr = listenLine.replace('LISTENING ', '').trim(); + relayHttp = `http://${addr}`; + relayWsBase = `ws://${addr}`; + }); + + afterAll(() => { + relayProc?.kill(); + }); + + it('0-Writeback Gate: JS TestWorkspace loads all 11 blocks + 6 surface elements with 0 outbound writeback updates', async () => { + const room = 'room-zero-writeback'; + const rustClientId = 2 ** 41 + 101; + const driver = new RustDriver(relayHttp, room, rustClientId); + await driver.waitReady(); + + await driver.call({ + cmd: 'seed_full_schema', + page_id: 'doc:home', + title: 'Zero Writeback Doc', + }); + + const outboundUpdates: Array<{ + docId: string; + kind: 'step2' | 'update'; + bytes: number[]; + }> = []; + + const roomClient = new RoomWebSocketClient( + `${relayWsBase}/native-sync/rooms/${room}`, + { + onOutboundDocFrame: (docId, kind, bytes) => { + const isEmpty = + bytes.byteLength === 0 || + (bytes.byteLength === 2 && bytes[0] === 0 && bytes[1] === 0); + if (!isEmpty) { + outboundUpdates.push({ docId, kind, bytes: Array.from(bytes) }); + } + }, + } + ); + + const schema = new Schema(); + schema.register(AffineSchemas); + + const workspace = new TestWorkspace({ + id: room, + docSources: { main: roomClient.createDocSource() }, + awarenessSources: [roomClient.createAwarenessSource()], + blobSources: { + main: new MemoryBlobSource(), + shadows: [new MockServerBlobSource(room, relayHttp)], + }, + }); + workspace.storeExtensions = AffineSchemas.map(s => BlockSchemaExtension(s)); + workspace.start(); + + // Wait for root doc + doc:home meta to sync from Rust + await vi.waitFor( + () => { + expect(workspace.getDoc('doc:home')).not.toBeNull(); + }, + { timeout: 10_000 } + ); + + const doc = workspace.getDoc('doc:home')!; + const store = doc.getStore({ id: 'doc:home' }); + store.load(); + await workspace.waitForSynced(); + + // Verify all 12 blocks (11 types, 2 paragraphs) & all 6 surface elements loaded cleanly in real Store/SyncController + expect(store.root?.flavour).toBe('affine:page'); + const yBlocks = doc.spaceDoc.getMap('blocks'); + expect(yBlocks.size).toBe(12); + + // Instantiate every block via SyncController-equivalent schema check: verify every non-undefined default prop exists! + for (const [, yBlock] of yBlocks.entries()) { + const blockMap = yBlock as Y.Map; + const flavour = blockMap.get('sys:flavour') as string; + const blockSchema = schema.flavourSchemaMap.get(flavour); + expect(blockSchema, `schema registered for ${flavour}`).toBeDefined(); + + // Check sys:version matches exact AffineSchemas version + expect(blockMap.get('sys:version')).toBe(blockSchema!.version); + + // Check every non-undefined default prop is already present (0 writeback guarantee) + const defaultProps = blockSchema!.model.props?.({ + Text: () => ({}) as never, + Boxed: (v: unknown) => v as never, + }); + if (defaultProps) { + for (const [key, value] of Object.entries(defaultProps)) { + if (value !== undefined) { + expect( + blockMap.has(`prop:${key}`), + `Missing default prop:${key} on ${flavour} would trigger JS SyncController writeback` + ).toBe(true); + } + } + } + } + + // Verify 0 non-empty outbound writeback updates were emitted by JS + expect(outboundUpdates).toEqual([]); + + workspace.forceStop(); + workspace.dispose(); + roomClient.close(); + await driver.quit(); + }); + + it('1,000-Step Deterministic Seeded Concurrent Fuzz converges L0 (StateVector, DeleteSet, doc.json, Blob, Awareness)', async () => { + const room = 'room-fuzz-1000'; + const rustClientId = 2 ** 42 + 7; + const jsClientId = 2 ** 43 + 9; + expect(jsClientId).toBeGreaterThan(2 ** 32); + + const driver = new RustDriver(relayHttp, room, rustClientId); + await driver.waitReady(); + + await driver.call({ + cmd: 'seed_full_schema', + page_id: 'doc:home', + title: 'Fuzz 1000', + }); + + const roomClient = new RoomWebSocketClient( + `${relayWsBase}/native-sync/rooms/${room}` + ); + const mockBlob = new MockServerBlobSource(room, relayHttp); + const workspace = new TestWorkspace({ + id: room, + docSources: { main: roomClient.createDocSource() }, + awarenessSources: [roomClient.createAwarenessSource()], + blobSources: { + main: new MemoryBlobSource(), + shadows: [mockBlob], + }, + }); + // Enforce 53-bit > 2^32 clientID on JS root doc and awareness + workspace.doc.clientID = jsClientId; + workspace.awarenessStore.awareness.clientID = jsClientId; + workspace.awarenessStore.setLocalState({ + user: { name: 'JS Peer' }, + color: '#22cc88', + selectionV2: {}, + }); + workspace.start(); + + await vi.waitFor( + () => { + expect(workspace.getDoc('doc:home')).not.toBeNull(); + }, + { timeout: 10_000 } + ); + + const doc = workspace.getDoc('doc:home')!; + doc.spaceDoc.clientID = jsClientId; + doc.load(); + await workspace.waitForSynced(); + + // Awareness bidirectional visibility with mandatory top-level color + valid TextSelection in selectionV2 + workspace.awarenessStore.setLocalState({ + user: { name: 'JS Peer' }, + color: '#22cc88', + selectionV2: { + 'doc:home': [ + { + type: 'text', + from: { blockId: 'p-2', index: 1, length: 0 }, + to: null, + }, + ], + }, + }); + await driver.call({ + cmd: 'set_awareness', + name: 'Rust Peer', + color: '#ff4400', + store_key: 'doc:home', + block_id: 'p-1', + index: 2, + length: 3, + now_ms: 1_000, + }); + + await vi.waitFor( + () => { + const rustState = workspace.awarenessStore + .getStates() + .get(rustClientId); + expect(rustState?.color).toBe('#ff4400'); + const rawSel = rustState?.selectionV2?.['doc:home']?.[0] as + | Record + | undefined; + expect(rawSel).toBeDefined(); + const parsed = TextSelection.fromJSON(rawSel!); + expect(parsed.from).toEqual({ blockId: 'p-1', index: 2, length: 3 }); + expect(parsed.to).toBeNull(); + }, + { timeout: 5_000 } + ); + + await driver.call({ cmd: 'drain', wait_ms: 150 }); + const preFuzzRust = await driver.call<{ + remoteAwareness: Record; + }>({ cmd: 'export_state', page_id: 'doc:home' }); + expect(preFuzzRust.remoteAwareness[String(jsClientId)]?.color).toBe( + '#22cc88' + ); + + // Blob roundtrip across Rust <-> JS via bs-relay + const blobBytes = [10, 20, 30, 40, 50, 60]; + await driver.call({ + cmd: 'upload_blob', + key: 'shared-img', + bytes: blobBytes, + }); + const fetchedByJs = await mockBlob.get('shared-img'); + expect(fetchedByJs).not.toBeNull(); + expect( + Array.from(new Uint8Array(await fetchedByJs!.arrayBuffer())) + ).toEqual(blobBytes); + + // 1,000-step deterministic seeded concurrent fuzz (500 JS + 500 Rust interleaved) + const rand = createMulberry32(0x2026_1000); + const yBlocks = doc.spaceDoc.getMap('blocks'); + const textBlockIds = ['p-1', 'p-2', 'l-1', 'c-1']; + const reorderBlockIds = ['p-1', 'p-2', 'l-1', 'd-1', 'c-1']; + + const t0 = performance.now(); + for (let step = 0; step < 1_000; step += 1) { + const isJs = rand() < 0.5; + const blockId = + textBlockIds[Math.floor(rand() * textBlockIds.length)] ?? 'p-2'; + const op = Math.floor(rand() * 6); + const nowMs = 2_000 + step * 5; + + if (isJs) { + doc.spaceDoc.transact(() => { + const yBlock = yBlocks.get(blockId) as Y.Map | undefined; + const yText = yBlock?.get('prop:text') as Y.Text | undefined; + if (op === 0 && yText) { + const idx = Math.floor(rand() * (yText.length + 1)); + const ch = String.fromCharCode(65 + (step % 26)); + yText.insert(idx, ch); + } else if (op === 1 && yText && yText.length > 0) { + const idx = Math.floor(rand() * yText.length); + const del = Math.min( + yText.length - idx, + 1 + Math.floor(rand() * 2) + ); + yText.delete(idx, del); + } else if (op === 2 && yText && yText.length > 0) { + const idx = Math.floor(rand() * yText.length); + const len = Math.min( + yText.length - idx, + 1 + Math.floor(rand() * 3) + ); + yText.format(idx, len, { bold: step % 2 === 0 ? true : null }); + } else if (op === 3) { + const note = yBlocks.get('note-1') as Y.Map; + const children = note.get('sys:children') as Y.Array; + const arr = children.toArray(); + const pick = + reorderBlockIds[Math.floor(rand() * reorderBlockIds.length)]!; + const oldIdx = arr.indexOf(pick); + if (oldIdx >= 0 && arr.length > 1) { + const nextIdx = Math.floor(rand() * (arr.length - 1)); + children.delete(oldIdx, 1); + children.insert(nextIdx, [pick]); + } + } else if (op === 4) { + const surface = yBlocks.get('surface-1') as Y.Map; + const elementsBox = surface.get('prop:elements') as Y.Map; + const elements = elementsBox.get('value') as Y.Map>; + const shape = elements.get('el-shape'); + shape?.set( + 'xywh', + `[${Math.floor(rand() * 400)},${Math.floor(rand() * 400)},120,80]` + ); + } else if (op === 5) { + const surface = yBlocks.get('surface-1') as Y.Map; + const elementsBox = surface.get('prop:elements') as Y.Map; + const elements = elementsBox.get('value') as Y.Map>; + const conn = elements.get('el-conn'); + conn?.set('mode', step % 3); + } + }); + } else { + if (op === 0) { + await driver.call({ + cmd: 'insert_text', + page_id: 'doc:home', + block_id: blockId, + index: Math.floor(rand() * 20), + text: String.fromCharCode(97 + (step % 26)), + now_ms: nowMs, + }); + } else if (op === 1) { + await driver.call({ + cmd: 'remove_text', + page_id: 'doc:home', + block_id: blockId, + index: Math.floor(rand() * 15), + len: 1 + Math.floor(rand() * 2), + now_ms: nowMs, + }); + } else if (op === 2) { + await driver.call({ + cmd: 'format_text', + page_id: 'doc:home', + block_id: blockId, + index: Math.floor(rand() * 15), + len: 1 + Math.floor(rand() * 3), + bold: step % 2 === 0, + now_ms: nowMs, + }); + } else if (op === 3) { + const pick = + reorderBlockIds[Math.floor(rand() * reorderBlockIds.length)]!; + await driver.call({ + cmd: 'reorder_child', + page_id: 'doc:home', + parent_id: 'note-1', + child_id: pick, + new_index: Math.floor(rand() * 4), + now_ms: nowMs, + }); + } else if (op === 4) { + await driver.call({ + cmd: 'update_shape_xywh', + page_id: 'doc:home', + surface_id: 'surface-1', + element_id: 'el-shape', + xywh: `[${Math.floor(rand() * 400)},${Math.floor(rand() * 400)},120,80]`, + now_ms: nowMs, + }); + } else { + await driver.call({ + cmd: 'update_connector_mode', + page_id: 'doc:home', + surface_id: 'surface-1', + element_id: 'el-conn', + mode: step % 3, + now_ms: nowMs, + }); + } + } + + // Mid-flight disconnect & reconnect on Rust side at step 500 + if (step === 500) { + await driver.call({ cmd: 'reconnect' }); + } + } + + // Converge both ends cleanly + await workspace.waitForSynced(); + await driver.call({ cmd: 'sync_all' }); + await driver.call({ cmd: 'drain', wait_ms: 200 }); + await workspace.waitForSynced(); + await driver.call({ cmd: 'sync_all' }); + const elapsedMs = Math.round(performance.now() - t0); + + const rustExport = await driver.call<{ + stateVector: Record; + fullUpdateV1: number[]; + docJson: unknown; + }>({ cmd: 'export_state', page_id: 'doc:home' }); + + const rustDeleteSet = exportDeleteSetFromUpdate( + new Uint8Array(rustExport.fullUpdateV1) + ); + const jsStateVector = exportJsStateVector(doc.spaceDoc); + const jsDeleteSet = exportJsDeleteSet(doc.spaceDoc); + const jsDocJson = exportJsDocJson(doc.spaceDoc); + + // L0 Convergence Assertions + expect(rustExport.stateVector).toEqual(jsStateVector); + expect(rustDeleteSet).toEqual(jsDeleteSet); + expect(rustExport.docJson).toEqual(jsDocJson); + expect(workspace.docSync.status.main?.pendingPushUpdates ?? 0).toBe(0); + expect(workspace.docSync.status.main?.pendingPullUpdates ?? 0).toBe(0); + + // Awareness +30s expiry check on Rust deterministic clock + const tickRes = await driver.call<{ + expired: number[]; + activeRemotes: number[]; + }>({ cmd: 'tick_awareness', now_ms: 35_000 }); + expect(tickRes.expired).toContain(jsClientId); + expect(tickRes.activeRemotes).toEqual([]); + + // Log convergence timing for verification reporting + expect(elapsedMs).toBeGreaterThanOrEqual(0); + + workspace.forceStop(); + workspace.dispose(); + roomClient.close(); + await driver.quit(); + }); + + it('Concurrent multi-peer claimSeed starter init produces exactly 1 doc:home and 1 affine:page root (zero duplicate seeding)', async () => { + const room = 'room-concurrent-seed'; + const peers = Array.from({ length: 3 }, () => { + const client = new RoomWebSocketClient( + `${relayWsBase}/native-sync/rooms/${room}` + ); + const workspace = new TestWorkspace({ + id: room, + docSources: { main: client.createDocSource() }, + awarenessSources: [client.createAwarenessSource()], + blobSources: { + main: new MemoryBlobSource(), + shadows: [new MockServerBlobSource(room, relayHttp)], + }, + }); + workspace.storeExtensions = AffineSchemas.map(s => + BlockSchemaExtension(s) + ); + workspace.start(); + return { client, workspace }; + }); + + const results = await Promise.all( + peers.map(({ client, workspace }) => + initRoomDocWithSeed({ + collection: workspace, + roomClient: client, + docId: 'doc:home', + seedKey: 'seed:doc:home', + seed: () => { + const doc = workspace.createDoc('doc:home'); + const store = doc.getStore({ id: 'doc:home' }); + store.load(); + const rootId = store.addBlock('affine:page', { + title: new Text('Single Seeded Page'), + }); + store.addBlock('affine:surface', {}, rootId); + const noteId = store.addBlock('affine:note', {}, rootId); + store.addBlock( + 'affine:paragraph', + { text: new Text('hello') }, + noteId + ); + }, + }) + ) + ); + + // Exactly one peer wins the room seed CAS + expect(results.filter(r => r.seeded).length).toBe(1); + + // All 3 peers converge on a single doc:home with exactly 1 affine:page root block + for (const { workspace } of peers) { + await workspace.waitForSynced(); + const doc = workspace.getDoc('doc:home'); + expect(doc).not.toBeNull(); + await vi.waitFor( + () => { + const yBlocks = doc!.spaceDoc.getMap('blocks'); + const pageBlocks = Array.from(yBlocks.values()).filter( + b => (b as Y.Map).get('sys:flavour') === 'affine:page' + ); + expect(pageBlocks.length).toBe(1); + expect(yBlocks.size).toBe(4); + }, + { timeout: 10_000 } + ); + expect(workspace.meta.docMetas.length).toBe(1); + } + + for (const { client, workspace } of peers) { + workspace.forceStop(); + workspace.dispose(); + client.close(); + } + }); + + it('Delayed sync (>1.5s) and partial-seed winner disconnect recover cleanly to 1 meta.pages entry and 1 doc:home page', async () => { + // Part A: Delayed initial sync > 1.5s while connected must NOT trigger a duplicate local seed. + const slowRoom = 'room-delayed-seed'; + const slowPeers = Array.from({ length: 2 }, () => { + const client = new RoomWebSocketClient( + `${relayWsBase}/native-sync/rooms/${slowRoom}` + ); + const workspace = new TestWorkspace({ + id: slowRoom, + docSources: { main: client.createDocSource() }, + awarenessSources: [client.createAwarenessSource()], + blobSources: { main: new MemoryBlobSource() }, + }); + workspace.storeExtensions = AffineSchemas.map(s => + BlockSchemaExtension(s) + ); + workspace.start(); + return { client, workspace }; + }); + + const slowResults = await Promise.all( + slowPeers.map(({ client, workspace }, idx) => + initRoomDocWithSeed({ + collection: { + getDoc: id => workspace.getDoc(id), + waitForSynced: async () => { + if (idx === 1) { + await new Promise(resolve => setTimeout(resolve, 1_700)); + } + await workspace.waitForSynced(); + }, + meta: workspace.meta, + }, + roomClient: client, + docId: 'doc:home', + seedKey: 'seed:doc:home', + seed: () => { + const doc = workspace.createDoc('doc:home'); + const store = doc.getStore({ id: 'doc:home' }); + store.load(); + const rootId = store.addBlock('affine:page', { + title: new Text('Delayed Sync Single Seed'), + }); + store.addBlock('affine:surface', {}, rootId); + const noteId = store.addBlock('affine:note', {}, rootId); + store.addBlock( + 'affine:paragraph', + { text: new Text('single') }, + noteId + ); + }, + }) + ) + ); + expect(slowResults.filter(r => r.seeded).length).toBe(1); + for (const { workspace, client } of slowPeers) { + await workspace.waitForSynced(); + expect(workspace.meta.docMetas.length).toBe(1); + workspace.forceStop(); + workspace.dispose(); + client.close(); + } + + // Part B: Winner pushes meta.pages for doc:home and disconnects BEFORE seeding doc:home. + // Waiter #1 (survivor) is promoted and populates doc:home in-place via Proxy reuse while + // Waiter #2 (observer) receives winner=false, waits for affine:page root, and BOTH converge + // to 1 meta.pages entry and 4 blocks without destroying spaces['doc:home']. + const partialRoom = 'room-partial-seed-recovery'; + const makePeer = () => { + const client = new RoomWebSocketClient( + `${relayWsBase}/native-sync/rooms/${partialRoom}` + ); + const workspace = new TestWorkspace({ + id: partialRoom, + docSources: { main: client.createDocSource() }, + awarenessSources: [client.createAwarenessSource()], + blobSources: { main: new MemoryBlobSource() }, + }); + workspace.storeExtensions = AffineSchemas.map(s => + BlockSchemaExtension(s) + ); + workspace.start(); + return { client, workspace }; + }; + + const { client: winnerClient, workspace: winnerWs } = makePeer(); + const { client: survivorClient, workspace: survivorWs } = makePeer(); + const { client: observerClient, workspace: observerWs } = makePeer(); + + await Promise.all([ + winnerWs.waitForSynced(), + survivorWs.waitForSynced(), + observerWs.waitForSynced(), + ]); + + // Winner claims seed:doc:home, creates only the meta.pages entry (no doc:home blocks), + // waits for root sync to push meta.pages, then disconnects abruptly. + expect(await winnerClient.claimSeed('seed:doc:home')).toBe(true); + winnerWs.meta.initialize(); + winnerWs.createDoc('doc:home'); + await winnerWs.waitForSynced(); + + // Wait until BOTH survivor and observer receive the partial meta.pages entry. + await vi.waitFor( + () => { + expect(survivorWs.getDoc('doc:home')).not.toBeNull(); + expect(observerWs.getDoc('doc:home')).not.toBeNull(); + }, + { timeout: 5_000 } + ); + + const presetStyleSeed = (ws: TestWorkspace) => { + const existing = ws.getDoc('doc:home'); + const targetWs = + existing && !hasUsablePageRoot(existing) + ? (() => { + let claimed = false; + return new Proxy(ws, { + get(target, prop, receiver) { + if (prop === 'getDoc') { + return (id: string) => + id === 'doc:home' && !claimed ? null : target.getDoc(id); + } + if (prop === 'createDoc') { + return (id?: string) => { + if (id === 'doc:home' && !claimed) { + claimed = true; + return existing; + } + return target.createDoc(id); + }; + } + const val = Reflect.get(target, prop, receiver); + return typeof val === 'function' ? val.bind(target) : val; + }, + }); + })() + : ws; + + // Exact preset.ts pattern: checks hasDoc before populating blocks + let doc = targetWs.getDoc('doc:home'); + const hasDoc = !!doc; + if (!doc) { + doc = targetWs.createDoc('doc:home'); + } + const store = doc.getStore({ id: 'doc:home' }); + store.load(); + if (!hasDoc) { + const rootId = store.addBlock('affine:page', { + title: new Text('Recovered Page'), + }); + store.addBlock('affine:surface', {}, rootId); + const noteId = store.addBlock('affine:note', {}, rootId); + store.addBlock( + 'affine:paragraph', + { text: new Text('recovered') }, + noteId + ); + } + }; + + // Survivor enqueues first (Waiter #1), then Observer enqueues second (Waiter #2). + const survivorInitPromise = initRoomDocWithSeed({ + collection: survivorWs, + roomClient: survivorClient, + docId: 'doc:home', + seedKey: 'seed:doc:home', + seed: () => presetStyleSeed(survivorWs), + }); + await new Promise(resolve => setTimeout(resolve, 60)); + const observerInitPromise = initRoomDocWithSeed({ + collection: observerWs, + roomClient: observerClient, + docId: 'doc:home', + seedKey: 'seed:doc:home', + seed: () => presetStyleSeed(observerWs), + }); + + // Give both waiters a moment to enqueue their claims, then drop the abandoned winner. + await new Promise(resolve => setTimeout(resolve, 100)); + winnerWs.forceStop(); + winnerWs.dispose(); + winnerClient.close(); + + const [survivorResult, observerResult] = await Promise.all([ + survivorInitPromise, + observerInitPromise, + ]); + expect(survivorResult).toEqual({ seeded: true, offlineFallback: false }); + expect(observerResult).toEqual({ seeded: false, offlineFallback: false }); + + for (const ws of [survivorWs, observerWs]) { + await ws.waitForSynced(); + expect(ws.meta.docMetas.length).toBe(1); + const recoveredDoc = ws.getDoc('doc:home')!; + const recoveredBlocks = recoveredDoc.spaceDoc.getMap('blocks'); + const recoveredPages = Array.from(recoveredBlocks.values()).filter( + b => (b as Y.Map).get('sys:flavour') === 'affine:page' + ); + expect(recoveredPages.length).toBe(1); + expect(recoveredBlocks.size).toBe(4); + } + + survivorWs.forceStop(); + survivorWs.dispose(); + survivorClient.close(); + observerWs.forceStop(); + observerWs.dispose(); + observerClient.close(); + }); + + it('JS dropConnection() mid-edit reconnects with L0 convergence and live bidirectional awareness', async () => { + const room = 'room-js-drop-reconnect'; + const rustClientId = 2 ** 44 + 11; + const jsClientId = 2 ** 44 + 22; + + const driver = new RustDriver(relayHttp, room, rustClientId); + await driver.waitReady(); + await driver.call({ + cmd: 'seed_full_schema', + page_id: 'doc:home', + title: 'JS Reconnect Doc', + }); + + const roomClient = new RoomWebSocketClient( + `${relayWsBase}/native-sync/rooms/${room}` + ); + const workspace = new TestWorkspace({ + id: room, + docSources: { main: roomClient.createDocSource() }, + awarenessSources: [roomClient.createAwarenessSource()], + blobSources: { + main: new MemoryBlobSource(), + shadows: [new MockServerBlobSource(room, relayHttp)], + }, + }); + workspace.doc.clientID = jsClientId; + workspace.awarenessStore.awareness.clientID = jsClientId; + workspace.awarenessStore.setLocalState({ + user: { name: 'JS Reconnector' }, + color: '#11aa99', + selectionV2: { + 'doc:home': [ + { + type: 'text', + from: { blockId: 'p-2', index: 0, length: 0 }, + to: null, + }, + ], + }, + }); + workspace.start(); + + await vi.waitFor( + () => { + expect(workspace.getDoc('doc:home')).not.toBeNull(); + }, + { timeout: 10_000 } + ); + + const doc = workspace.getDoc('doc:home')!; + doc.spaceDoc.clientID = jsClientId; + doc.load(); + await workspace.waitForSynced(); + + await driver.call({ + cmd: 'set_awareness', + name: 'Rust Steady', + color: '#ee5522', + store_key: 'doc:home', + block_id: 'p-1', + index: 1, + length: 2, + now_ms: 1_000, + }); + await driver.call({ cmd: 'drain', wait_ms: 100 }); + + // Force-drop the JS WebSocket connection mid-session! + roomClient.dropConnection(); + + // Perform concurrent edits on BOTH JS and Rust while JS is disconnected. + doc.spaceDoc.transact(() => { + const yBlocks = doc.spaceDoc.getMap('blocks'); + const p2 = yBlocks.get('p-2') as Y.Map; + const yText = p2.get('prop:text') as Y.Text; + yText.insert(yText.length, ' [js-offline-edit]'); + }); + + await driver.call({ + cmd: 'insert_text', + page_id: 'doc:home', + block_id: 'p-1', + index: 0, + text: '[rust-while-js-down] ', + now_ms: 2_000, + }); + + // Wait for SyncPeer's automatic reconnect loop (5s backoff) to reconnect and converge. + await vi.waitFor( + async () => { + await driver.call({ cmd: 'drain', wait_ms: 100 }); + const rustState = await driver.call<{ + stateVector: Record; + fullUpdateV1: number[]; + docJson: unknown; + remoteAwareness: Record; + }>({ cmd: 'export_state', page_id: 'doc:home' }); + + expect(rustState.stateVector).toEqual( + exportJsStateVector(doc.spaceDoc) + ); + expect( + exportDeleteSetFromUpdate(new Uint8Array(rustState.fullUpdateV1)) + ).toEqual(exportJsDeleteSet(doc.spaceDoc)); + expect(rustState.docJson).toEqual(exportJsDocJson(doc.spaceDoc)); + + // Live awareness must be restored on BOTH sides (+2 clock re-announce on JS reconnect)! + expect(rustState.remoteAwareness[String(jsClientId)]?.color).toBe( + '#11aa99' + ); + const rustOnJs = workspace.awarenessStore.getStates().get(rustClientId); + expect(rustOnJs?.color).toBe('#ee5522'); + }, + { timeout: 15_000, interval: 250 } + ); + + workspace.forceStop(); + workspace.dispose(); + roomClient.close(); + await driver.quit(); + }, 20_000); + + it('Cross-origin blob CORS preflight (OPTIONS 204) and MockServerBlobSource upload -> Rust fetch', async () => { + const room = 'room-blob-cors-e2e'; + const blobUrl = `${relayHttp}/api/collection/${room}/blob/cross-origin-asset`; + + const preflight = await fetch(blobUrl, { method: 'OPTIONS' }); + expect(preflight.status).toBe(204); + expect(preflight.headers.get('access-control-allow-origin')).toBe('*'); + expect(preflight.headers.get('access-control-allow-methods')).toContain( + 'PUT' + ); + expect(preflight.headers.get('access-control-allow-headers')).toBe( + 'Content-Type' + ); + + const mockBlob = new MockServerBlobSource(room, relayHttp); + const payload = new Uint8Array([1, 2, 3, 4, 5, 42, 99]); + await mockBlob.set( + 'cross-origin-asset', + new Blob([payload], { type: 'application/octet-stream' }) + ); + + const driver = new RustDriver(relayHttp, room, 2 ** 44 + 33); + await driver.waitReady(); + const fetched = await driver.call<{ ok: boolean; bytes: number[] }>({ + cmd: 'fetch_blob', + key: 'cross-origin-asset', + }); + expect(fetched.ok).toBe(true); + expect(fetched.bytes).toEqual(Array.from(payload)); + + await driver.quit(); + }); +}); diff --git a/blocksuite/playground/apps/_common/sync/room/index.ts b/blocksuite/playground/apps/_common/sync/room/index.ts new file mode 100644 index 0000000000..a24a155480 --- /dev/null +++ b/blocksuite/playground/apps/_common/sync/room/index.ts @@ -0,0 +1,694 @@ +import type { AwarenessSource, DocSource } from '@blocksuite/sync'; +import type { Awareness } from 'y-protocols/awareness'; +import { + applyAwarenessUpdate, + encodeAwarenessUpdate, + removeAwarenessStates, +} from 'y-protocols/awareness'; +import * as syncProtocol from 'y-protocols/sync'; + +const FRAME_TAG_DOC = 0x00; +const FRAME_TAG_AWARENESS = 0x01; +const SYNC_MSG_DOC = 0; +const ROOM_AWARENESS_ORIGIN = 'room'; + +const textEncoder = new TextEncoder(); +const textDecoder = new TextDecoder(); + +function pushVarUint(out: number[], value: number) { + let num = value; + while (num > 0x7f) { + out.push(0x80 | (num & 0x7f)); + num = Math.floor(num / 128); + } + out.push(num & 0x7f); +} + +function pushVarBytes(out: number[], bytes: Uint8Array) { + pushVarUint(out, bytes.byteLength); + for (let i = 0; i < bytes.byteLength; i += 1) { + out.push(bytes[i]!); + } +} + +function pushVarString(out: number[], value: string) { + pushVarBytes(out, textEncoder.encode(value)); +} + +function readVarUint( + bytes: Uint8Array, + cursor: { offset: number } +): number | null { + let num = 0; + let mult = 1; + while (cursor.offset < bytes.byteLength) { + const byte = bytes[cursor.offset]!; + cursor.offset += 1; + num += (byte & 0x7f) * mult; + if (byte < 0x80) { + return num; + } + mult *= 128; + } + return null; +} + +function readVarBytes( + bytes: Uint8Array, + cursor: { offset: number } +): Uint8Array | null { + const len = readVarUint(bytes, cursor); + if (len === null || cursor.offset + len > bytes.byteLength) { + return null; + } + const slice = bytes.subarray(cursor.offset, cursor.offset + len); + cursor.offset += len; + return slice; +} + +export type RoomControlFrame = + | { type: 'seed-claim'; key: string } + | { type: 'seed-claim-result'; key: string; winner: boolean } + | { type: 'ready'; docId: string }; + +function encodeRoomDocFrame( + docId: string, + step: number, + payload: Uint8Array +): Uint8Array { + const out: number[] = [FRAME_TAG_DOC]; + pushVarString(out, docId); + pushVarUint(out, SYNC_MSG_DOC); + pushVarUint(out, step); + pushVarBytes(out, payload); + return new Uint8Array(out); +} + +export function encodeRoomDocStep1( + docId: string, + stateVector: Uint8Array +): Uint8Array { + return encodeRoomDocFrame( + docId, + syncProtocol.messageYjsSyncStep1, + stateVector + ); +} + +export function encodeRoomDocStep2( + docId: string, + diff: Uint8Array +): Uint8Array { + return encodeRoomDocFrame(docId, syncProtocol.messageYjsSyncStep2, diff); +} + +export function encodeRoomDocUpdate( + docId: string, + update: Uint8Array +): Uint8Array { + return encodeRoomDocFrame(docId, syncProtocol.messageYjsUpdate, update); +} + +export function encodeRoomAwarenessFrame(payload: Uint8Array): Uint8Array { + const out = new Uint8Array(1 + payload.byteLength); + out[0] = FRAME_TAG_AWARENESS; + out.set(payload, 1); + return out; +} + +type DecodedRoomBinaryFrame = + | { + kind: 'doc'; + docId: string; + step: number; + payload: Uint8Array; + } + | { + kind: 'awareness'; + payload: Uint8Array; + }; + +function decodeRoomBinaryFrame( + bytes: Uint8Array +): DecodedRoomBinaryFrame | null { + if (bytes.byteLength === 0) return null; + const tag = bytes[0]; + if (tag === FRAME_TAG_AWARENESS) { + return { + kind: 'awareness', + payload: bytes.subarray(1), + }; + } + if (tag === FRAME_TAG_DOC) { + const cursor = { offset: 1 }; + const docIdBytes = readVarBytes(bytes, cursor); + if (!docIdBytes) return null; + const docId = textDecoder.decode(docIdBytes); + const outerType = readVarUint(bytes, cursor); + if (outerType !== SYNC_MSG_DOC) { + return null; + } + const step = readVarUint(bytes, cursor); + if (step === null) return null; + const payload = readVarBytes(bytes, cursor); + if (!payload) return null; + return { kind: 'doc', docId, step, payload }; + } + return null; +} + +interface PendingPull { + step2?: Uint8Array; + hubSv?: Uint8Array; + resolve: (value: { data: Uint8Array; state: Uint8Array }) => void; + reject: (err: Error) => void; +} + +interface PendingSeedClaim { + resolve: (winner: boolean) => void; + reject: (err: Error) => void; +} + +export interface RoomWebSocketClientOptions { + /** Optional hook called whenever a doc update or reverse step2 is sent. */ + onOutboundDocFrame?: ( + docId: string, + kind: 'step2' | 'update', + bytes: Uint8Array + ) => void; +} + +export class RoomWebSocketClient { + private _ws: WebSocket | null = null; + private _openPromise: Promise | null = null; + private _closed = false; + private _hasOpenedOnce = false; + + private readonly _pendingPulls = new Map(); + private readonly _pendingSeedClaims = new Map(); + private readonly _docSubscribers = new Set< + (docId: string, data: Uint8Array) => void + >(); + private readonly _disconnectListeners = new Set<(reason: string) => void>(); + private readonly _reconnectListeners = new Set<() => void>(); + private readonly _awarenessListeners = new Set< + (payload: Uint8Array) => void + >(); + + constructor( + readonly url: string, + private readonly _options: RoomWebSocketClientOptions = {} + ) {} + + async ensureConnected(): Promise { + await this._ensureSocket(); + } + + private _ensureSocket(): Promise { + if (this._closed) { + return Promise.reject(new Error('RoomWebSocketClient is closed')); + } + if (this._ws && this._ws.readyState === WebSocket.OPEN) { + return Promise.resolve(this._ws); + } + if (this._openPromise) { + return this._openPromise; + } + + this._openPromise = new Promise((resolve, reject) => { + const ws = new WebSocket(this.url); + ws.binaryType = 'arraybuffer'; + this._ws = ws; + + const onOpen = () => { + ws.removeEventListener('error', onOpenError); + const isReconnect = this._hasOpenedOnce; + this._hasOpenedOnce = true; + resolve(ws); + if (isReconnect) { + for (const cb of this._reconnectListeners) { + cb(); + } + } + }; + const onOpenError = () => { + ws.removeEventListener('open', onOpen); + this._openPromise = null; + if (this._ws === ws) { + this._ws = null; + } + const err = new Error(`WebSocket connection failed: ${this.url}`); + this._rejectAllPending(err); + reject(err); + }; + + ws.addEventListener('open', onOpen, { once: true }); + ws.addEventListener('error', onOpenError, { once: true }); + ws.addEventListener('message', event => { + this._handleMessage(event.data).catch(() => {}); + }); + ws.addEventListener('close', event => { + if (this._ws === ws) { + this._ws = null; + this._openPromise = null; + } + const reason = event.reason || `code:${event.code}`; + this._rejectAllPending(new Error(`WebSocket closed (${reason})`)); + for (const cb of this._disconnectListeners) { + cb(reason); + } + }); + }); + + return this._openPromise; + } + + private _rejectAllPending(err: Error) { + for (const [, pending] of this._pendingPulls) { + pending.reject(err); + } + this._pendingPulls.clear(); + + for (const [, list] of this._pendingSeedClaims) { + for (const item of list) { + item.reject(err); + } + } + this._pendingSeedClaims.clear(); + } + + private async _handleMessage(raw: unknown) { + if (typeof raw === 'string') { + try { + const frame = JSON.parse(raw) as RoomControlFrame; + if (frame.type === 'seed-claim-result') { + const list = this._pendingSeedClaims.get(frame.key); + const first = list?.shift(); + if (list && list.length === 0) { + this._pendingSeedClaims.delete(frame.key); + } + first?.resolve(frame.winner); + } + } catch { + // Ignore malformed control frames. + } + return; + } + + let bytes: Uint8Array; + if (raw instanceof ArrayBuffer) { + bytes = new Uint8Array(raw); + } else if (ArrayBuffer.isView(raw)) { + bytes = new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength); + } else if (typeof Blob !== 'undefined' && raw instanceof Blob) { + bytes = new Uint8Array(await raw.arrayBuffer()); + } else { + return; + } + + const decoded = decodeRoomBinaryFrame(bytes); + if (!decoded) return; + + if (decoded.kind === 'awareness') { + for (const listener of this._awarenessListeners) { + listener(decoded.payload); + } + return; + } + + const { docId, step, payload } = decoded; + if (step === syncProtocol.messageYjsSyncStep2) { + const pending = this._pendingPulls.get(docId); + if (pending) { + pending.step2 = payload; + if (pending.hubSv) { + this._pendingPulls.delete(docId); + pending.resolve({ data: pending.step2, state: pending.hubSv }); + } + } else { + for (const cb of this._docSubscribers) { + cb(docId, payload); + } + } + } else if (step === syncProtocol.messageYjsSyncStep1) { + const pending = this._pendingPulls.get(docId); + if (pending) { + pending.hubSv = payload; + if (pending.step2) { + this._pendingPulls.delete(docId); + pending.resolve({ data: pending.step2, state: pending.hubSv }); + } + } + } else if (step === syncProtocol.messageYjsUpdate) { + for (const cb of this._docSubscribers) { + cb(docId, payload); + } + } + } + + async sendBinary(bytes: Uint8Array): Promise { + const ws = await this._ensureSocket(); + if (ws.readyState !== WebSocket.OPEN) { + throw new Error('WebSocket is not open'); + } + ws.send(bytes.slice()); + } + + async claimSeed(key: string): Promise { + const ws = await this._ensureSocket(); + return new Promise((resolve, reject) => { + const list = this._pendingSeedClaims.get(key) ?? []; + list.push({ resolve, reject }); + this._pendingSeedClaims.set(key, list); + ws.send( + JSON.stringify({ type: 'seed-claim', key } satisfies RoomControlFrame) + ); + }); + } + + /** Force-drop the current socket (useful for reconnect testing) without permanently closing the client. */ + dropConnection() { + if (this._ws) { + this._ws.close(4000, 'simulated-disconnect'); + this._ws = null; + this._openPromise = null; + } + } + + close() { + this._closed = true; + this._rejectAllPending(new Error('RoomWebSocketClient closed')); + if (this._ws) { + this._ws.close(); + this._ws = null; + } + this._openPromise = null; + } + + createDocSource(): DocSource { + return { + name: 'room-websocket', + pull: async (docId: string, state: Uint8Array) => { + const ws = await this._ensureSocket(); + return new Promise<{ data: Uint8Array; state: Uint8Array }>( + (resolve, reject) => { + const existing = this._pendingPulls.get(docId); + if (existing) { + existing.reject(new Error(`Superseded pull for ${docId}`)); + } + this._pendingPulls.set(docId, { resolve, reject }); + ws.send(encodeRoomDocStep1(docId, state).slice()); + } + ); + }, + finishPull: async (docId: string, diffToStorage: Uint8Array) => { + this._options.onOutboundDocFrame?.(docId, 'step2', diffToStorage); + await this.sendBinary(encodeRoomDocStep2(docId, diffToStorage)); + }, + push: async (docId: string, data: Uint8Array) => { + this._options.onOutboundDocFrame?.(docId, 'update', data); + await this.sendBinary(encodeRoomDocUpdate(docId, data)); + }, + subscribe: async (cb, disconnect) => { + await this._ensureSocket(); + this._docSubscribers.add(cb); + this._disconnectListeners.add(disconnect); + return () => { + this._docSubscribers.delete(cb); + this._disconnectListeners.delete(disconnect); + }; + }, + }; + } + + createAwarenessSource(): AwarenessSource { + let connectedAwareness: Awareness | null = null; + let onLocalUpdate: + | (( + changes: { added: number[]; updated: number[]; removed: number[] }, + origin: unknown + ) => void) + | null = null; + let onRemotePayload: ((payload: Uint8Array) => void) | null = null; + let onReconnect: (() => void) | null = null; + + return { + connect: (awareness: Awareness) => { + connectedAwareness = awareness; + + onLocalUpdate = (changes, origin) => { + if (origin === ROOM_AWARENESS_ORIGIN) return; + const changedClients = [ + ...changes.added, + ...changes.updated, + ...changes.removed, + ]; + if (changedClients.length === 0) return; + const encoded = encodeAwarenessUpdate(awareness, changedClients); + void this.sendBinary(encodeRoomAwarenessFrame(encoded)).catch( + () => {} + ); + }; + + onRemotePayload = (payload: Uint8Array) => { + applyAwarenessUpdate(awareness, payload, ROOM_AWARENESS_ORIGIN); + }; + + onReconnect = () => { + if (!connectedAwareness) return; + const cur = connectedAwareness.getLocalState(); + if (cur !== null) { + // Bump local awareness clock by >= +2 so it strictly exceeds the hub's + // disconnect tombstone (old_clock + 1) and restores live cursor presence. + connectedAwareness.setLocalState({ ...cur }); + connectedAwareness.setLocalState(cur); + } + }; + + awareness.on('update', onLocalUpdate); + this._awarenessListeners.add(onRemotePayload); + this._reconnectListeners.add(onReconnect); + + // Broadcast current local awareness state once socket is open. + if (awareness.meta.has(awareness.clientID)) { + const initial = encodeAwarenessUpdate(awareness, [ + awareness.clientID, + ]); + void this.sendBinary(encodeRoomAwarenessFrame(initial)).catch( + () => {} + ); + } + }, + disconnect: () => { + // Never close the shared WebSocket here — only detach awareness listeners. + // Remove awareness state BEFORE detaching onLocalUpdate so explicit disconnect + // broadcasts the removal frame to live peers. + if (connectedAwareness && onLocalUpdate) { + removeAwarenessStates( + connectedAwareness, + [connectedAwareness.clientID], + 'disconnect' + ); + connectedAwareness.off('update', onLocalUpdate); + } + if (onRemotePayload) { + this._awarenessListeners.delete(onRemotePayload); + } + if (onReconnect) { + this._reconnectListeners.delete(onReconnect); + } + connectedAwareness = null; + onLocalUpdate = null; + onRemotePayload = null; + onReconnect = null; + }, + }; + } +} + +export interface RoomSeedDocHandle { + loaded: boolean; + load(): unknown; + spaceDoc?: { + getMap(name: string): { + values(): Iterable; + }; + on?(event: 'update', cb: () => void): void; + off?(event: 'update', cb: () => void): void; + }; +} + +export interface RoomSeedCollection { + getDoc(id: string): RoomSeedDocHandle | null; + waitForSynced(): Promise; + meta: { + initialize(): void; + docMetaAdded: { + subscribe(cb: (docId: string) => void): { unsubscribe(): void }; + }; + }; +} + +export interface InitRoomDocWithSeedOptions { + collection: RoomSeedCollection; + roomClient: RoomWebSocketClient; + docId: string; + seedKey: string; + seed: () => Promise | void; + /** + * When true, fall back to a detached local standalone seed ONLY if the initial + * WebSocket connection itself fails (e.g. `bs-relay` is not running). + */ + allowOfflineFallback?: boolean; + /** Invoked when initial socket connection fails and offline fallback is taken. */ + onOfflineFallback?: () => void; +} + +export function hasUsablePageRoot(doc: RoomSeedDocHandle | null): boolean { + if (!doc?.spaceDoc) return false; + const blocks = doc.spaceDoc.getMap('blocks'); + for (const value of blocks.values()) { + if ( + value && + typeof value === 'object' && + 'get' in value && + typeof (value as { get: unknown }).get === 'function' && + (value as { get(k: string): unknown }).get('sys:flavour') === + 'affine:page' + ) { + return true; + } + } + return false; +} + +async function waitForUsablePageRoot(doc: RoomSeedDocHandle): Promise { + if (hasUsablePageRoot(doc)) return; + const spaceDoc = doc.spaceDoc; + if (!spaceDoc?.on || !spaceDoc.off) return; + + await new Promise(resolve => { + const onUpdate = () => { + if (hasUsablePageRoot(doc)) { + spaceDoc.off?.('update', onUpdate); + resolve(); + } + }; + spaceDoc.on?.('update', onUpdate); + if (hasUsablePageRoot(doc)) { + spaceDoc.off?.('update', onUpdate); + resolve(); + } + }); +} + +async function waitForDocArrival( + collection: RoomSeedCollection, + docId: string +): Promise { + const existing = collection.getDoc(docId); + if (existing) return existing; + + return new Promise(resolve => { + let settled = false; + const finish = (doc: RoomSeedDocHandle) => { + if (settled) return; + settled = true; + sub.unsubscribe(); + resolve(doc); + }; + + const sub = collection.meta.docMetaAdded.subscribe(addedId => { + if (addedId === docId) { + const arrived = collection.getDoc(docId); + if (arrived) { + finish(arrived); + } + } + }); + + // Re-check immediately in case doc arrived between initial check and subscribe. + const now = collection.getDoc(docId); + if (now) { + finish(now); + } + }); +} + +/** + * Coordinate initial document seeding across peers in a room using WebSocket + * `seed-claim` / `seed-claim-result` CAS arbitration. + * + * - Falls back to a detached offline standalone workspace ONLY when the initial + * WebSocket connection itself fails (`allowOfflineFallback: true`). + * - Once connected, waits for initial sync (never timing out into local seeding). + * - If `docId` already exists with a usable `affine:page` root, loads it without re-seeding. + * - Otherwise claims `seedKey` over WebSocket: only the single winner seeds `docId`, + * while non-winners wait for `docId` to arrive and load it. + */ +export async function initRoomDocWithSeed({ + collection, + roomClient, + docId, + seedKey, + seed, + allowOfflineFallback = false, + onOfflineFallback, +}: InitRoomDocWithSeedOptions): Promise<{ + seeded: boolean; + offlineFallback: boolean; +}> { + try { + await roomClient.ensureConnected(); + } catch (err) { + if (allowOfflineFallback) { + // Permanently close the room client so an offline seed is never pushed into a live room later. + roomClient.close(); + onOfflineFallback?.(); + collection.meta.initialize(); + await seed(); + const doc = collection.getDoc(docId); + if (doc && !doc.loaded) { + doc.load(); + } + return { seeded: true, offlineFallback: true }; + } + throw err; + } + + await collection.waitForSynced(); + + const existing = collection.getDoc(docId); + if (existing) { + if (!existing.loaded) { + existing.load(); + } + await collection.waitForSynced(); + if (hasUsablePageRoot(existing)) { + return { seeded: false, offlineFallback: false }; + } + } + + const winner = await roomClient.claimSeed(seedKey); + if (winner) { + collection.meta.initialize(); + await seed(); + const doc = collection.getDoc(docId); + if (doc && !doc.loaded) { + doc.load(); + } + await collection.waitForSynced(); + return { seeded: true, offlineFallback: false }; + } + + const arrived = await waitForDocArrival(collection, docId); + if (!arrived.loaded) { + arrived.load(); + } + await collection.waitForSynced(); + if (arrived.spaceDoc && !hasUsablePageRoot(arrived)) { + await waitForUsablePageRoot(arrived); + await collection.waitForSynced(); + } + return { seeded: false, offlineFallback: false }; +} diff --git a/blocksuite/playground/apps/starter/utils/collection.ts b/blocksuite/playground/apps/starter/utils/collection.ts index f31a37c851..c78aba8980 100644 --- a/blocksuite/playground/apps/starter/utils/collection.ts +++ b/blocksuite/playground/apps/starter/utils/collection.ts @@ -7,6 +7,7 @@ import { TestWorkspace, } from '@blocksuite/affine/store/test'; import { + type AwarenessSource, type BlobSource, BroadcastChannelAwarenessSource, BroadcastChannelDocSource, @@ -16,12 +17,50 @@ import { import * as Y from 'yjs'; import { MockServerBlobSource } from '../../_common/sync/blob/mock-server.js'; +import { + hasUsablePageRoot, + initRoomDocWithSeed, + RoomWebSocketClient, +} from '../../_common/sync/room/index.js'; import type { InitFn } from '../data/utils.js'; const params = new URLSearchParams(location.search); const room = params.get('room'); +const wsParam = params.get('ws'); +const envRelayUrl = + (import.meta as { env?: Record }).env + ?.PLAYGROUND_RELAY_URL ?? null; +const explicitRelayWs = wsParam || envRelayUrl; const isE2E = room?.startsWith('playwright'); const blobSourceArgs = (params.get('blobSource') ?? '').split(','); +const roomClients = new WeakMap(); + +function resolveRoomWsUrl(roomName: string, explicitWs: string | null) { + if (explicitWs) { + return explicitWs; + } + const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:'; + return `${protocol}//${location.host}/native-sync/rooms/${encodeURIComponent(roomName)}`; +} + +function resolveRelayHttpOrigin(explicitWs: string | null): string { + if (!explicitWs) { + return ''; + } + try { + const parsed = new URL(explicitWs); + if (parsed.protocol === 'ws:' || parsed.protocol === 'wss:') { + const httpProto = parsed.protocol === 'wss:' ? 'https:' : 'http:'; + return `${httpProto}//${parsed.host}`; + } + if (parsed.protocol === 'http:' || parsed.protocol === 'https:') { + return `${parsed.protocol}//${parsed.host}`; + } + } catch { + // Fall back to relative origin if the override is not a full URL. + } + return ''; +} export function createStarterDocCollection( storeExtensionManager: StoreExtensionManager @@ -31,20 +70,41 @@ export function createStarterDocCollection( schema.register(AffineSchemas); const idGenerator = isE2E ? createAutoIncrementIdGenerator() : nanoid; + const useRoomWs = Boolean(explicitRelayWs || (room && !isE2E)); + const id = room ?? `starter-${Math.random().toString(16).slice(2, 8)}`; + let docSources: DocCollectionOptions['docSources']; - if (room) { + let roomClient: RoomWebSocketClient | null = null; + const awarenessSources: AwarenessSource[] = [ + new BroadcastChannelAwarenessSource(id), + ]; + + if (useRoomWs) { + roomClient = new RoomWebSocketClient( + resolveRoomWsUrl(collectionId, explicitRelayWs) + ); + docSources = { + main: roomClient.createDocSource(), + shadows: [ + new BroadcastChannelDocSource(`broadcast-channel-${collectionId}`), + ], + }; + awarenessSources.push(roomClient.createAwarenessSource()); + } else if (room) { docSources = { main: new BroadcastChannelDocSource(`broadcast-channel-${room}`), }; } - const id = room ?? `starter-${Math.random().toString(16).slice(2, 8)}`; const blobSources = { main: new MemoryBlobSource(), shadows: [] as BlobSource[], } satisfies DocCollectionOptions['blobSources']; - if (blobSourceArgs.includes('mock')) { - blobSources.shadows.push(new MockServerBlobSource(collectionId)); + if (useRoomWs || blobSourceArgs.includes('mock')) { + const relayHttpOrigin = resolveRelayHttpOrigin(explicitRelayWs); + blobSources.shadows.push( + new MockServerBlobSource(collectionId, relayHttpOrigin) + ); } if (blobSourceArgs.includes('idb')) { blobSources.shadows.push(new IndexedDBBlobSource(collectionId)); @@ -53,11 +113,14 @@ export function createStarterDocCollection( const options: DocCollectionOptions = { id: collectionId, idGenerator, - awarenessSources: [new BroadcastChannelAwarenessSource(id)], + awarenessSources, docSources, blobSources, }; const collection = new TestWorkspace(options); + if (roomClient) { + roomClients.set(collection, roomClient); + } collection.storeExtensions = storeExtensionManager.get('store'); collection.start(); @@ -89,8 +152,59 @@ export async function initStarterDocCollection(collection: TestWorkspace) { ).forEach(fn => functionMap.set(fn.id, fn)); const init = params.get('init') || 'preset'; if (functionMap.has(init)) { + const initFn = functionMap.get(init); + const roomClient = roomClients.get(collection); + if (roomClient) { + await initRoomDocWithSeed({ + collection, + roomClient, + docId: 'doc:home', + seedKey: 'seed:doc:home', + seed: async () => { + // If a previous winner pushed meta.pages for doc:home and disconnected + // before seeding doc:home's blocks, reuse the existing doc:home in-place + // without calling removeDoc (which would destroy spaces['doc:home'] on other peers). + const existing = collection.getDoc('doc:home'); + if (existing && !hasUsablePageRoot(existing)) { + let claimedExisting = false; + const seedCollection = new Proxy(collection, { + get(target, prop, receiver) { + if (prop === 'getDoc') { + return (id: string) => { + if (id === 'doc:home' && !claimedExisting) { + return null; + } + return target.getDoc(id); + }; + } + if (prop === 'createDoc') { + return (id?: string) => { + if (id === 'doc:home' && !claimedExisting) { + claimedExisting = true; + return existing; + } + return target.createDoc(id); + }; + } + const val = Reflect.get(target, prop, receiver); + return typeof val === 'function' ? val.bind(target) : val; + }, + }); + await initFn?.(seedCollection, 'doc:home'); + } else { + await initFn?.(collection, 'doc:home'); + } + }, + allowOfflineFallback: !explicitRelayWs, + onOfflineFallback: () => { + collection.forceStop(); + }, + }); + return; + } + collection.meta.initialize(); - await functionMap.get(init)?.(collection, 'doc:home'); + await initFn?.(collection, 'doc:home'); const doc = collection.getDoc('doc:home'); if (!doc?.loaded) { doc?.load(); diff --git a/blocksuite/playground/vite.config.ts b/blocksuite/playground/vite.config.ts index f4dea70e08..522fa5be6f 100644 --- a/blocksuite/playground/vite.config.ts +++ b/blocksuite/playground/vite.config.ts @@ -46,9 +46,28 @@ const clearSiteDataPlugin = () => // https://vitejs.dev/config/ export default defineConfig(({ mode }) => { process.env = { ...process.env, ...loadEnv(mode, __dirname, '') }; + const relayTarget = + process.env.PLAYGROUND_RELAY_URL ?? 'http://127.0.0.1:8788'; + const roomProxy = { + '/native-sync': { + target: relayTarget, + ws: true, + changeOrigin: true, + }, + '/api/collection': { + target: relayTarget, + changeOrigin: true, + }, + }; return { envDir: __dirname, + server: { + proxy: roomProxy, + }, + preview: { + proxy: roomProxy, + }, define: { 'import.meta.env.PLAYGROUND_SERVER': JSON.stringify( process.env.PLAYGROUND_SERVER ?? 'http://localhost:8787' diff --git a/blocksuite/playground/vitest.config.ts b/blocksuite/playground/vitest.config.ts new file mode 100644 index 0000000000..76932dcb8c --- /dev/null +++ b/blocksuite/playground/vitest.config.ts @@ -0,0 +1,14 @@ +import { vanillaExtractPlugin } from '@vanilla-extract/vite-plugin'; + +export default { + esbuild: { + target: 'es2022', + }, + plugins: [vanillaExtractPlugin()], + test: { + include: ['apps/_common/sync/room/__tests__/**/*.spec.ts'], + testTimeout: 60_000, + hookTimeout: 30_000, + restoreMocks: true, + }, +};