mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-05 11:15:01 +03:00
feat(native-playground): add y-octo doc engine, binary room sync, and unified workspace
Unifies the 3-crate native-playground workspace (ui, doc, playground) with: - crates/doc (#![forbid(unsafe_code)], y-octo 0.3.0, 53-bit JS-safe client IDs, full block & surface element schemas with 0-writeback defaults, blocks-scoped undo/redo with SelectionSnapshot, deterministic RoomAwareness with BlockSuite TextSelectionState, Sans-I/O binary room framing, Axum room hub / bs-relay with WS-only seed-claim FIFO waiter promotion & equal-clock awareness refcount hardening & permissive blob CORS, and bs_doc_driver). - @blocksuite/sync DocPeer finishPull listener ordering (preserving 0-writeback while capturing mid-handshake edits) and pendingIncomingUpdates subdoc buffer. - @blocksuite/playground RoomWebSocketClient (+2 awareness clock re-announce on reconnect, disconnect removal before detaching listener, socket-only detached offline fallback, in-place Proxy reuse for partial-seed recovery without destroying shared subdocs, winner flush & non-winner affine:page root wait, ?ws= relay origin forwarding to MockServerBlobSource) + live Rust-JS E2E convergence suite. - Real doc_1k_edits_ms and room_sync_1k_ops_ms benchmarks in bs-harness bench. - Updated check-invariants.sh (doc GUI isolation + forbid(unsafe_code)), AGENTS.md active invariants, and native-playground CI workflow (wasm32 doc check, macOS doc tests, and parallel js-room-coop job).
This commit is contained in:
1 parent
74bcafa70f
commit
4e26a040ee
26 files changed
+8658
-60
No files matched your search
@@ -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)
|
||||
@@ -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<void>(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<void>(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<void>(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();
|
||||
});
|
||||
});
|
||||
@@ -114,6 +114,7 @@ export class SyncPeer {
|
||||
|
||||
readonly state: {
|
||||
connectedDocs: Map<string, Doc>;
|
||||
pendingIncomingUpdates: Map<string, Uint8Array[]>;
|
||||
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();
|
||||
|
||||
@@ -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> | void;
|
||||
push(docId: string, data: Uint8Array): Promise<void> | void;
|
||||
|
||||
/**
|
||||
|
||||
@@ -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:<docId>`), `?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
|
||||
|
||||
Generated
+1185
-30
File diff suppressed because it is too large.
Load diff
@@ -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"
|
||||
|
||||
@@ -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"]
|
||||
@@ -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<u8>,
|
||||
},
|
||||
FetchBlob {
|
||||
key: String,
|
||||
},
|
||||
Drain {
|
||||
wait_ms: u64,
|
||||
},
|
||||
ExportState {
|
||||
page_id: String,
|
||||
},
|
||||
Quit,
|
||||
}
|
||||
|
||||
type WsStream =
|
||||
tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
|
||||
|
||||
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::<String>();
|
||||
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<String, u64> = sv
|
||||
.iter()
|
||||
.map(|(cid, clk)| (cid.to_string(), *clk))
|
||||
.collect();
|
||||
let doc_json = page.export_doc_json().unwrap();
|
||||
let remote_awareness: std::collections::BTreeMap<String, JsonValue> = 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();
|
||||
}
|
||||
}
|
||||
@@ -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<TextRangePoint>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub reverse: Option<bool>,
|
||||
}
|
||||
|
||||
impl TextSelectionState {
|
||||
pub fn caret(block_id: impl Into<String>, 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<TextRangePoint>, 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<String, Vec<serde_json::Value>>,
|
||||
}
|
||||
|
||||
impl AwarenessPayload {
|
||||
pub fn new(name: impl Into<String>, color: impl Into<String>) -> Self {
|
||||
Self {
|
||||
user: AwarenessUser { name: name.into() },
|
||||
color: color.into(),
|
||||
selection_v2: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_selection(
|
||||
&mut self,
|
||||
store_key: impl Into<String>,
|
||||
selections: Vec<serde_json::Value>,
|
||||
) {
|
||||
self.selection_v2.insert(store_key.into(), selections);
|
||||
}
|
||||
|
||||
pub fn set_text_selection(
|
||||
&mut self,
|
||||
store_key: impl Into<String>,
|
||||
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<Vec<u8>>,
|
||||
/// Remote client IDs expired during this tick.
|
||||
pub expired_clients: Vec<u64>,
|
||||
/// 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<u64>,
|
||||
remote_last_seen_ms: BTreeMap<u64, u64>,
|
||||
}
|
||||
|
||||
impl RoomAwareness {
|
||||
pub fn new(local_client_id: u64) -> DocResult<Self> {
|
||||
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<Vec<u8>> {
|
||||
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<Vec<u8>> {
|
||||
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<AwarenessEvent> {
|
||||
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<Vec<u8>> {
|
||||
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<AwarenessPayload> {
|
||||
let state = self.inner.get_states().get(&client_id)?;
|
||||
if state.is_deleted() {
|
||||
return None;
|
||||
}
|
||||
serde_json::from_str::<AwarenessPayload>(state.content()).ok()
|
||||
}
|
||||
|
||||
/// List all currently active (non-deleted) remote client IDs.
|
||||
pub fn active_remote_clients(&self) -> Vec<u64> {
|
||||
let local_id = self.inner.local_id();
|
||||
let mut ids: Vec<u64> = 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<AwarenessTick> {
|
||||
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<u64> = 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,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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<dyn std::error::Error>> {
|
||||
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(())
|
||||
}
|
||||
@@ -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<u64, DocError> {
|
||||
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<T = ()> = Result<T, DocError>;
|
||||
@@ -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<Message>;
|
||||
|
||||
enum SeedClaimState {
|
||||
Pending {
|
||||
winner_conn_id: ConnId,
|
||||
waiters: VecDeque<ConnId>,
|
||||
},
|
||||
Completed,
|
||||
}
|
||||
|
||||
fn doc_id_from_seed_key(key: &str) -> Option<&str> {
|
||||
key.strip_prefix("seed:")
|
||||
}
|
||||
|
||||
struct RoomState {
|
||||
docs: HashMap<String, DocSession<()>>,
|
||||
/// `doc_id -> set of subscribed connection IDs`
|
||||
subscriptions: HashMap<String, HashSet<ConnId>>,
|
||||
/// Active connections in this room.
|
||||
conns: HashMap<ConnId, OutboundTx>,
|
||||
/// Single-winner CAS claims for initial seeding (`key -> Pending | Completed`).
|
||||
seed_claims: HashMap<String, SeedClaimState>,
|
||||
/// 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<u64, HashSet<ConnId>>,
|
||||
/// Reverse index: `conn_id -> set of client_ids` announced on that connection.
|
||||
conn_clients: HashMap<ConnId, HashSet<u64>>,
|
||||
/// 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<u8>, exclude: Option<ConnId>) {
|
||||
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<u8>, exclude: Option<ConnId>) {
|
||||
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<u8>) {
|
||||
// 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<u64> = 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<u64> = 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<String> = 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<String>);
|
||||
type BlobMap = HashMap<BlobKey, BlobEntry>;
|
||||
|
||||
/// Shared state for the single-port `bs_room` HTTP + WebSocket Hub.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct RoomHub {
|
||||
rooms: Arc<Mutex<HashMap<String, Arc<Mutex<RoomState>>>>>,
|
||||
blobs: Arc<Mutex<BlobMap>>,
|
||||
next_conn_id: Arc<AtomicU64>,
|
||||
}
|
||||
|
||||
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<Mutex<RoomState>> {
|
||||
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<String>,
|
||||
State(hub): State<RoomHub>,
|
||||
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::<Message>();
|
||||
|
||||
{
|
||||
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<RoomHub>) -> 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<RoomHub>,
|
||||
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<RoomHub>,
|
||||
) -> Response {
|
||||
let mut guard = hub.blobs.lock().await;
|
||||
guard.remove(&(id, key));
|
||||
with_blob_cors(StatusCode::OK.into_response())
|
||||
}
|
||||
@@ -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<String>,
|
||||
},
|
||||
Paragraph {
|
||||
paragraph_type: ParagraphType,
|
||||
text: String,
|
||||
},
|
||||
List {
|
||||
list_type: ListType,
|
||||
text: String,
|
||||
checked: bool,
|
||||
order: Option<i32>,
|
||||
},
|
||||
Divider,
|
||||
Code {
|
||||
text: String,
|
||||
language: Option<String>,
|
||||
caption: String,
|
||||
},
|
||||
Image {
|
||||
source_id: String,
|
||||
caption: String,
|
||||
width: f64,
|
||||
height: f64,
|
||||
xywh: Option<String>,
|
||||
},
|
||||
Bookmark {
|
||||
url: String,
|
||||
title: Option<String>,
|
||||
description: Option<String>,
|
||||
},
|
||||
Frame {
|
||||
title: String,
|
||||
xywh: Option<String>,
|
||||
presentation_index: Option<String>,
|
||||
},
|
||||
EdgelessText {
|
||||
xywh: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
#[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<i64>,
|
||||
pub children: Vec<String>,
|
||||
pub prop_keys: Vec<String>,
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
},
|
||||
Connector {
|
||||
mode: i32,
|
||||
seed: i32,
|
||||
source: ConnectorEndpointSpec,
|
||||
target: ConnectorEndpointSpec,
|
||||
text: Option<String>,
|
||||
/// Only persisted when explicitly moved locally; `None` by default.
|
||||
label_xywh: Option<[f64; 4]>,
|
||||
},
|
||||
Brush {
|
||||
seed: i32,
|
||||
points: Vec<Vec<f64>>,
|
||||
xywh: String,
|
||||
},
|
||||
Highlighter {
|
||||
seed: i32,
|
||||
points: Vec<Vec<f64>>,
|
||||
xywh: String,
|
||||
},
|
||||
Text {
|
||||
seed: i32,
|
||||
text: String,
|
||||
xywh: String,
|
||||
},
|
||||
Group {
|
||||
seed: i32,
|
||||
title: String,
|
||||
children: Vec<String>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ConnectorEndpointSpec {
|
||||
pub id: Option<String>,
|
||||
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<String>, 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<Any> 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 {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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<M = SelectionSnapshot> {
|
||||
pub commits: Vec<SessionCommit<M>>,
|
||||
/// Any local `FormattingCleanup` commits produced during integration that
|
||||
/// MUST be forwarded to outbound sync.
|
||||
pub outbound_updates: Vec<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
}
|
||||
|
||||
/// Per-page CRDT session wrapping `DocSession<SelectionSnapshot>` with an
|
||||
/// `UndoStackId` scoped strictly to the `blocks` root `Y.Map`.
|
||||
pub struct PageDocSession {
|
||||
session: DocSession<SelectionSnapshot>,
|
||||
undo_stack_id: UndoStackId,
|
||||
blocks_target: TypeTarget,
|
||||
}
|
||||
|
||||
impl PageDocSession {
|
||||
pub fn new(page_id: impl Into<String>, client_id: u64) -> DocResult<Self> {
|
||||
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<SelectionSnapshot> {
|
||||
&self.session
|
||||
}
|
||||
|
||||
pub fn inner_mut(&mut self) -> &mut DocSession<SelectionSnapshot> {
|
||||
&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<Vec<u8>> {
|
||||
Ok(self.session.encode_state_vector_v1()?)
|
||||
}
|
||||
|
||||
pub fn encode_update_v1(&self) -> DocResult<Vec<u8>> {
|
||||
Ok(self.session.encode_update_v1()?)
|
||||
}
|
||||
|
||||
pub fn encode_diff_v1(&self, remote_sv: &[u8]) -> DocResult<Vec<u8>> {
|
||||
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<RemoteApplyResult> {
|
||||
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<String>,
|
||||
spec: BlockSpec,
|
||||
parent_id: Option<&str>,
|
||||
index: Option<u64>,
|
||||
now_ms: u64,
|
||||
) -> DocResult<Option<SessionCommit<SelectionSnapshot>>> {
|
||||
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<Option<SessionCommit<SelectionSnapshot>>> {
|
||||
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<Option<SessionCommit<SelectionSnapshot>>> {
|
||||
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<Option<SessionCommit<SelectionSnapshot>>> {
|
||||
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<Option<SessionCommit<SelectionSnapshot>>> {
|
||||
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<Option<SessionCommit<SelectionSnapshot>>> {
|
||||
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<String>,
|
||||
value: SessionValue,
|
||||
now_ms: u64,
|
||||
) -> DocResult<Option<SessionCommit<SelectionSnapshot>>> {
|
||||
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<String>,
|
||||
index: &str,
|
||||
spec: SurfaceElementSpec,
|
||||
now_ms: u64,
|
||||
) -> DocResult<Option<SessionCommit<SelectionSnapshot>>> {
|
||||
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<String>,
|
||||
value: SessionValue,
|
||||
now_ms: u64,
|
||||
) -> DocResult<Option<SessionCommit<SelectionSnapshot>>> {
|
||||
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<SelectionSnapshot> {
|
||||
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<bool> {
|
||||
Ok(self.session.set_stack_selection_meta(
|
||||
self.undo_stack_id,
|
||||
y_octo::UndoStack::Undo,
|
||||
snapshot,
|
||||
)?)
|
||||
}
|
||||
|
||||
pub fn undo(&mut self) -> DocResult<Option<SessionCommit<SelectionSnapshot>>> {
|
||||
Ok(self.session.undo_stack(self.undo_stack_id)?)
|
||||
}
|
||||
|
||||
pub fn redo(&mut self) -> DocResult<Option<SessionCommit<SelectionSnapshot>>> {
|
||||
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<UnknownBlock> {
|
||||
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<JsonValue> {
|
||||
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<JsonValue> {
|
||||
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<JsonValue> = 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<String, PageDocSession>,
|
||||
}
|
||||
|
||||
impl WorkspaceSession {
|
||||
pub fn new(room: impl Into<String>, client_id: u64) -> DocResult<Self> {
|
||||
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<Option<SessionCommit<()>>> {
|
||||
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<String>,
|
||||
title: impl Into<String>,
|
||||
create_date: i64,
|
||||
) -> DocResult<Option<SessionCommit<()>>> {
|
||||
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<RemoteApplyResult<()>> {
|
||||
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<Vec<PageMeta>> {
|
||||
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<Vec<u8>> {
|
||||
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<Vec<u8>> {
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<u8>),
|
||||
}
|
||||
|
||||
/// 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<Vec<u8>> {
|
||||
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<RoomBinaryFrame> {
|
||||
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<String> {
|
||||
Ok(serde_json::to_string(frame)?)
|
||||
}
|
||||
|
||||
/// Decode a text JSON control frame.
|
||||
pub fn decode_control_frame(text: &str) -> DocResult<RoomControlFrame> {
|
||||
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<Vec<u8>>,
|
||||
received_step2: bool,
|
||||
}
|
||||
|
||||
impl DocSyncState {
|
||||
pub fn new(doc_id: impl Into<String>) -> 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<u8>) -> 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<Vec<u8>> {
|
||||
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<u8>) -> Option<Vec<u8>> {
|
||||
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<u8>) -> 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<u8>) -> RoomBinaryFrame {
|
||||
RoomBinaryFrame::Doc {
|
||||
doc_id: self.doc_id.clone(),
|
||||
message: DocMessage::Update(update),
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
|
||||
@@ -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<f64>) -> 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<TimingStat> {
|
||||
// 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<TimingStat> {
|
||||
// 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<String>,
|
||||
@@ -403,6 +572,8 @@ fn run_bench(
|
||||
web_wasm_gzip: Option<u64>,
|
||||
) -> 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,
|
||||
|
||||
@@ -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/ \
|
||||
|
||||
@@ -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 });
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<WebSocket> | null = null;
|
||||
private _closed = false;
|
||||
private _hasOpenedOnce = false;
|
||||
|
||||
private readonly _pendingPulls = new Map<string, PendingPull>();
|
||||
private readonly _pendingSeedClaims = new Map<string, PendingSeedClaim[]>();
|
||||
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<void> {
|
||||
await this._ensureSocket();
|
||||
}
|
||||
|
||||
private _ensureSocket(): Promise<WebSocket> {
|
||||
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<WebSocket>((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<void> {
|
||||
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<boolean> {
|
||||
const ws = await this._ensureSocket();
|
||||
return new Promise<boolean>((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<unknown>;
|
||||
};
|
||||
on?(event: 'update', cb: () => void): void;
|
||||
off?(event: 'update', cb: () => void): void;
|
||||
};
|
||||
}
|
||||
|
||||
export interface RoomSeedCollection {
|
||||
getDoc(id: string): RoomSeedDocHandle | null;
|
||||
waitForSynced(): Promise<unknown>;
|
||||
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> | 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<void> {
|
||||
if (hasUsablePageRoot(doc)) return;
|
||||
const spaceDoc = doc.spaceDoc;
|
||||
if (!spaceDoc?.on || !spaceDoc.off) return;
|
||||
|
||||
await new Promise<void>(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<RoomSeedDocHandle> {
|
||||
const existing = collection.getDoc(docId);
|
||||
if (existing) return existing;
|
||||
|
||||
return new Promise<RoomSeedDocHandle>(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 };
|
||||
}
|
||||
@@ -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<string, string | undefined> }).env
|
||||
?.PLAYGROUND_RELAY_URL ?? null;
|
||||
const explicitRelayWs = wsParam || envRelayUrl;
|
||||
const isE2E = room?.startsWith('playwright');
|
||||
const blobSourceArgs = (params.get('blobSource') ?? '').split(',');
|
||||
const roomClients = new WeakMap<TestWorkspace, RoomWebSocketClient>();
|
||||
|
||||
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();
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
};
|
||||
Reference in new issue
Block a user