Spike yrs.wasm under wazero for Yjs compaction (ADR-3: go)
Compile yrs 0.28 to wasm32-wasip1 and run it in Go with wazero to compact Yjs update logs and extract ProseMirror JSON and plain text. Fixtures come from real Yjs, and y-prosemirror's output is the oracle. - Output matches y-prosemirror on every fixture; Yjs loads yrs snapshots - Snapshot + 200 updates compacts in 0.6-47 ms; WebAssembly costs at most 2x native - merge_updates is quadratic, so the server must compact incrementally Results and design rules are recorded in docs/adr/0003-yrs-wasm-wazero.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
03f3434c10
commit
4cb313aa95
18 files changed
+1778
-2
No files matched your search
@@ -0,0 +1,4 @@
|
||||
rust/target/
|
||||
go/docwell_yrs.wasm
|
||||
fixtures/node_modules/
|
||||
fixtures/data/
|
||||
@@ -0,0 +1,26 @@
|
||||
# Spike: yrs.wasm under wazero
|
||||
|
||||
Phase 0 go/no-go spike for ADR-3. Results and the decision are in [docs/adr/0003-yrs-wasm-wazero.md](../../docs/adr/0003-yrs-wasm-wazero.md).
|
||||
|
||||
This folder is outside `go.work` and the npm workspaces, so CI doesn't build it.
|
||||
|
||||
Requirements: Rust with the `wasm32-wasip1` target (`rustup target add wasm32-wasip1`), Go 1.26+, Node 22+.
|
||||
|
||||
```bash
|
||||
# 1. Build yrs.wasm and copy it next to the Go host
|
||||
sh build.sh
|
||||
|
||||
# 2. Generate the Yjs fixtures (from fixtures/)
|
||||
npm install && node generate.mjs
|
||||
|
||||
# 3. Tests and benchmarks (from go/; also writes the yrs snapshots that verify.mjs reads)
|
||||
GOWORK=off go test -v ./...
|
||||
GOWORK=off go test -run '^$' -bench . -benchtime=2s ./...
|
||||
YRS_TIMING=1 GOWORK=off go test -run TestTiming -v ./... # shows merge going quadratic
|
||||
|
||||
# 4. Check that Yjs loads what yrs wrote, and time Yjs itself (from fixtures/)
|
||||
node verify.mjs
|
||||
|
||||
# 5. Native yrs timings, to compare against WebAssembly (from rust/)
|
||||
cargo run --release --example native -- ../fixtures/data/medium.updates
|
||||
```
|
||||
@@ -0,0 +1,6 @@
|
||||
#!/usr/bin/env sh
|
||||
# Builds yrs.wasm and copies it next to the Go host, which embeds it.
|
||||
set -e
|
||||
cd "$(dirname "$0")"
|
||||
cargo build --manifest-path rust/Cargo.toml --release --target wasm32-wasip1
|
||||
cp rust/target/wasm32-wasip1/release/docwell_yrs.wasm go/docwell_yrs.wasm
|
||||
@@ -0,0 +1,183 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
//
|
||||
// Generates Yjs update logs shaped like Tiptap + y-prosemirror documents.
|
||||
// Writes <name>.updates (frames of [u32 LE length][update]) and <name>.json
|
||||
// (the expected ProseMirror JSON, from y-prosemirror itself).
|
||||
|
||||
import { writeFileSync } from 'node:fs'
|
||||
import * as Y from 'yjs'
|
||||
import { yXmlFragmentToProsemirrorJSON } from 'y-prosemirror'
|
||||
|
||||
const out = new URL('./data/', import.meta.url)
|
||||
|
||||
// Deterministic PRNG so fixtures are reproducible.
|
||||
function rng(seed) {
|
||||
return () => {
|
||||
seed = (seed + 0x6d2b79f5) | 0
|
||||
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed)
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
|
||||
}
|
||||
}
|
||||
|
||||
const WORDS = 'the quick brown fox jumps over lazy dog wiki page docwell żółć ünïcode 🙂 team space note draft review'.split(' ')
|
||||
|
||||
// Deletes like ProseMirror does: never through the middle of a surrogate pair.
|
||||
// (Yjs keeps a lone surrogate when you do; yrs does not, so the two would disagree.)
|
||||
function plain(text) {
|
||||
return text.toDelta().map((d) => d.insert).join('')
|
||||
}
|
||||
|
||||
function safeDelete(doc, text, index, length) {
|
||||
const s = plain(text)
|
||||
const isLow = (i) => i > 0 && i < s.length && s.charCodeAt(i) >= 0xdc00 && s.charCodeAt(i) <= 0xdfff
|
||||
if (isLow(index)) index--
|
||||
let end = index + length
|
||||
if (isLow(end)) end++
|
||||
if (end > index && end <= s.length) doc.transact(() => text.delete(index, end - index))
|
||||
}
|
||||
|
||||
function recorder(doc) {
|
||||
const updates = []
|
||||
doc.on('update', (u) => updates.push(u))
|
||||
return updates
|
||||
}
|
||||
|
||||
function newBlock(rand) {
|
||||
const r = rand()
|
||||
if (r < 0.15) {
|
||||
const h = new Y.XmlElement('heading')
|
||||
h.setAttribute('level', 1 + Math.floor(rand() * 3))
|
||||
const t = new Y.XmlText()
|
||||
h.insert(0, [t])
|
||||
return { node: h, text: t }
|
||||
}
|
||||
if (r < 0.3) {
|
||||
const list = new Y.XmlElement('bulletList')
|
||||
const item = new Y.XmlElement('listItem')
|
||||
const p = new Y.XmlElement('paragraph')
|
||||
const t = new Y.XmlText()
|
||||
p.insert(0, [t])
|
||||
item.insert(0, [p])
|
||||
list.insert(0, [item])
|
||||
return { node: list, text: t }
|
||||
}
|
||||
const p = new Y.XmlElement('paragraph')
|
||||
const t = new Y.XmlText()
|
||||
p.insert(0, [t])
|
||||
return { node: p, text: t }
|
||||
}
|
||||
|
||||
// One client types a document keystroke by keystroke, with typos, bold/link marks and deletions.
|
||||
function typing(name, seed, targetChars) {
|
||||
const rand = rng(seed)
|
||||
const doc = new Y.Doc()
|
||||
const updates = recorder(doc)
|
||||
const frag = doc.getXmlFragment('default')
|
||||
let chars = 0
|
||||
const texts = []
|
||||
while (chars < targetChars) {
|
||||
const { node, text } = newBlock(rand)
|
||||
doc.transact(() => frag.insert(frag.length, [node]))
|
||||
texts.push(text)
|
||||
const words = 5 + Math.floor(rand() * 60)
|
||||
for (let w = 0; w < words; w++) {
|
||||
const word = WORDS[Math.floor(rand() * WORDS.length)] + ' '
|
||||
for (const ch of word) {
|
||||
doc.transact(() => text.insert(text.length, ch))
|
||||
chars++
|
||||
}
|
||||
const backspace = rand() < 0.05 && text.length > 3
|
||||
if (backspace) {
|
||||
safeDelete(doc, text, text.length - 3, 3) // backspace x3
|
||||
}
|
||||
// Bold or link the word just typed (not after a backspace, which shifted it).
|
||||
if (!backspace && rand() < 0.04 && text.length > word.length) {
|
||||
const attrs = rand() < 0.5 ? { bold: {} } : { link: { href: 'https://example.com/' + w, target: '_blank' } }
|
||||
doc.transact(() => text.format(text.length - word.length, word.length - 1, attrs))
|
||||
}
|
||||
}
|
||||
// Occasionally edit an earlier block, or delete one.
|
||||
if (rand() < 0.1 && texts.length > 2) {
|
||||
const t = texts[Math.floor(rand() * (texts.length - 1))]
|
||||
if (t.length > 10) safeDelete(doc, t, Math.floor(rand() * (t.length - 5)), 4)
|
||||
}
|
||||
if (rand() < 0.03 && frag.length > 3) {
|
||||
const i = Math.floor(rand() * (frag.length - 1))
|
||||
doc.transact(() => frag.delete(i, 1))
|
||||
texts.splice(i, 1)
|
||||
}
|
||||
}
|
||||
save(name, doc, updates)
|
||||
}
|
||||
|
||||
// Three clients edit the same document concurrently and sync in random order.
|
||||
function concurrent(name, seed, rounds) {
|
||||
const rand = rng(seed)
|
||||
const docs = [new Y.Doc(), new Y.Doc(), new Y.Doc()]
|
||||
const server = new Y.Doc()
|
||||
const updates = recorder(server)
|
||||
const pending = docs.map(() => [])
|
||||
docs.forEach((d, i) => d.on('update', (u, origin) => { if (origin !== 'remote') pending[i].push(u) }))
|
||||
for (let r = 0; r < rounds; r++) {
|
||||
const i = Math.floor(rand() * docs.length)
|
||||
const d = docs[i]
|
||||
const frag = d.getXmlFragment('default')
|
||||
if (frag.length === 0 || rand() < 0.05) {
|
||||
const { node } = newBlock(rand)
|
||||
d.transact(() => frag.insert(Math.floor(rand() * (frag.length + 1)), [node]))
|
||||
} else {
|
||||
// Find some XmlText to edit.
|
||||
const block = frag.get(Math.floor(rand() * frag.length))
|
||||
let t = block
|
||||
while (t && !(t instanceof Y.XmlText)) t = t.get(0)
|
||||
if (t) {
|
||||
if (rand() < 0.85 || t.length < 2) {
|
||||
const word = WORDS[Math.floor(rand() * WORDS.length)] + ' '
|
||||
let at = Math.floor(rand() * (t.length + 1))
|
||||
const s = plain(t)
|
||||
if (at > 0 && at < s.length && s.charCodeAt(at) >= 0xdc00 && s.charCodeAt(at) <= 0xdfff) at--
|
||||
d.transact(() => t.insert(at, word))
|
||||
} else {
|
||||
const at = Math.floor(rand() * (t.length - 1))
|
||||
safeDelete(d, t, at, Math.min(3, t.length - at))
|
||||
}
|
||||
}
|
||||
}
|
||||
// Randomly deliver a client's pending updates to the server and the other clients.
|
||||
if (rand() < 0.3) {
|
||||
const j = Math.floor(rand() * docs.length)
|
||||
for (const u of pending[j]) {
|
||||
Y.applyUpdate(server, u, 'remote')
|
||||
docs.forEach((o, k) => k !== j && Y.applyUpdate(o, u, 'remote'))
|
||||
}
|
||||
pending[j] = []
|
||||
}
|
||||
}
|
||||
pending.forEach((p) => p.forEach((u) => Y.applyUpdate(server, u, 'remote')))
|
||||
save(name, server, updates)
|
||||
}
|
||||
|
||||
function save(name, doc, updates) {
|
||||
let size = 0
|
||||
for (const u of updates) size += 4 + u.length
|
||||
const buf = Buffer.alloc(size)
|
||||
let off = 0
|
||||
for (const u of updates) {
|
||||
buf.writeUInt32LE(u.length, off)
|
||||
buf.set(u, off + 4)
|
||||
off += 4 + u.length
|
||||
}
|
||||
writeFileSync(new URL(`${name}.updates`, out), buf)
|
||||
const json = yXmlFragmentToProsemirrorJSON(doc.getXmlFragment('default'))
|
||||
writeFileSync(new URL(`${name}.json`, out), JSON.stringify(json))
|
||||
const snapshot = Y.encodeStateAsUpdate(doc)
|
||||
console.log(`${name}: ${updates.length} updates, ${size} bytes log, ${snapshot.length} bytes yjs snapshot`)
|
||||
}
|
||||
|
||||
import { mkdirSync } from 'node:fs'
|
||||
mkdirSync(out, { recursive: true })
|
||||
typing('small', 1, 2_000)
|
||||
typing('medium', 2, 30_000)
|
||||
typing('large', 3, 250_000)
|
||||
concurrent('concurrent', 4, 20_000)
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
{
|
||||
"name": "yrs-wasm-fixtures",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "yrs-wasm-fixtures",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"dependencies": {
|
||||
"prosemirror-model": "^1.25.12",
|
||||
"prosemirror-state": "^1.4.4",
|
||||
"prosemirror-transform": "^1.12.4",
|
||||
"prosemirror-view": "^1.42.8",
|
||||
"y-prosemirror": "^1.3.7",
|
||||
"yjs": "^13.6.33"
|
||||
}
|
||||
},
|
||||
"node_modules/isomorphic.js": {
|
||||
"version": "0.2.5",
|
||||
"resolved": "https://registry.npmjs.org/isomorphic.js/-/isomorphic.js-0.2.5.tgz",
|
||||
"integrity": "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "GitHub Sponsors ❤",
|
||||
"url": "https://github.com/sponsors/dmonad"
|
||||
}
|
||||
},
|
||||
"node_modules/lib0": {
|
||||
"version": "0.2.119",
|
||||
"resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.119.tgz",
|
||||
"integrity": "sha512-vh+TiejVy8Xm+hCdnRfn9BthGNvNUZdEXltNjVZL3TzRIKP3s1lnQh8pWd/Q0wCgY0FPAGVVjFF4ZiHUV3LFgA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"isomorphic.js": "^0.2.4"
|
||||
},
|
||||
"bin": {
|
||||
"0ecdsa-generate-keypair": "bin/0ecdsa-generate-keypair.js",
|
||||
"0gentesthtml": "bin/gentesthtml.js",
|
||||
"0serve": "bin/0serve.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
},
|
||||
"funding": {
|
||||
"type": "GitHub Sponsors ❤",
|
||||
"url": "https://github.com/sponsors/dmonad"
|
||||
}
|
||||
},
|
||||
"node_modules/orderedmap": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/orderedmap/-/orderedmap-2.1.1.tgz",
|
||||
"integrity": "sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/prosemirror-model": {
|
||||
"version": "1.25.12",
|
||||
"resolved": "https://registry.npmjs.org/prosemirror-model/-/prosemirror-model-1.25.12.tgz",
|
||||
"integrity": "sha512-Ue2gTmXMa7EhpLNhC7J+h4+ykD8ha12K6rrZFFKKJHBForfIStw5gJ6Zrf1mqqAa9NmpmEB4wp9bKmA4eUVjWg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"orderedmap": "^2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/prosemirror-state": {
|
||||
"version": "1.4.4",
|
||||
"resolved": "https://registry.npmjs.org/prosemirror-state/-/prosemirror-state-1.4.4.tgz",
|
||||
"integrity": "sha512-6jiYHH2CIGbCfnxdHbXZ12gySFY/fz/ulZE333G6bPqIZ4F+TXo9ifiR86nAHpWnfoNjOb3o5ESi7J8Uz1jXHw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"prosemirror-model": "^1.0.0",
|
||||
"prosemirror-transform": "^1.0.0",
|
||||
"prosemirror-view": "^1.27.0"
|
||||
}
|
||||
},
|
||||
"node_modules/prosemirror-transform": {
|
||||
"version": "1.12.4",
|
||||
"resolved": "https://registry.npmjs.org/prosemirror-transform/-/prosemirror-transform-1.12.4.tgz",
|
||||
"integrity": "sha512-2/WuPum3pn+O/Vi2vzpi8210ICUe2kIPXdLYjQ09Pv5DtT5bcKWMJhAKPBwvpPjpp5iOYUVwVEr0gOM1BY1Mgw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"prosemirror-model": "^1.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/prosemirror-view": {
|
||||
"version": "1.42.8",
|
||||
"resolved": "https://registry.npmjs.org/prosemirror-view/-/prosemirror-view-1.42.8.tgz",
|
||||
"integrity": "sha512-ftDZjCs9AjAekXmCfJRn2U3IdlRCl0Yc4tZT1/jJWCsz4DiSifEBXtWmpJpw/4f1Rg328uAUQ+u2lCJ0+AVZkw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"prosemirror-model": "^1.25.12",
|
||||
"prosemirror-state": "^1.0.0",
|
||||
"prosemirror-transform": "^1.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/y-prosemirror": {
|
||||
"version": "1.3.7",
|
||||
"resolved": "https://registry.npmjs.org/y-prosemirror/-/y-prosemirror-1.3.7.tgz",
|
||||
"integrity": "sha512-NpM99WSdD4Fx4if5xOMDpPtU3oAmTSjlzh5U4353ABbRHl1HtAFUx6HlebLZfyFxXN9jzKMDkVbcRjqOZVkYQg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"lib0": "^0.2.109"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16.0.0",
|
||||
"npm": ">=8.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "GitHub Sponsors ❤",
|
||||
"url": "https://github.com/sponsors/dmonad"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"prosemirror-model": "^1.7.1",
|
||||
"prosemirror-state": "^1.2.3",
|
||||
"prosemirror-view": "^1.9.10",
|
||||
"y-protocols": "^1.0.1",
|
||||
"yjs": "^13.5.38"
|
||||
}
|
||||
},
|
||||
"node_modules/y-protocols": {
|
||||
"version": "1.0.7",
|
||||
"resolved": "https://registry.npmjs.org/y-protocols/-/y-protocols-1.0.7.tgz",
|
||||
"integrity": "sha512-YSVsLoXxO67J6eE/nV4AtFtT3QEotZf5sK5BHxFBXso7VDUT3Tx07IfA6hsu5Q5OmBdMkQVmFZ9QOA7fikWvnw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"lib0": "^0.2.85"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16.0.0",
|
||||
"npm": ">=8.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "GitHub Sponsors ❤",
|
||||
"url": "https://github.com/sponsors/dmonad"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"yjs": "^13.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/yjs": {
|
||||
"version": "13.6.33",
|
||||
"resolved": "https://registry.npmjs.org/yjs/-/yjs-13.6.33.tgz",
|
||||
"integrity": "sha512-q/UYvr1gOk4XII+Cu1CW2dINjYqJJFifTzogEaIARznrvX7uOlHsdTEXcnOBMuIsrCGEEKdNxi74kyMLZlKVfw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"lib0": "^0.2.99"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16.0.0",
|
||||
"npm": ">=8.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "GitHub Sponsors ❤",
|
||||
"url": "https://github.com/sponsors/dmonad"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "yrs-wasm-fixtures",
|
||||
"private": true,
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"prosemirror-model": "^1.25.12",
|
||||
"prosemirror-state": "^1.4.4",
|
||||
"prosemirror-transform": "^1.12.4",
|
||||
"prosemirror-view": "^1.42.8",
|
||||
"y-prosemirror": "^1.3.7",
|
||||
"yjs": "^13.6.33"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
//
|
||||
// Run after `go test` in ../go. Checks that Yjs loads the snapshots yrs wrote
|
||||
// (<name>.compact), and times the same operations in Yjs as a baseline.
|
||||
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { isDeepStrictEqual } from 'node:util'
|
||||
import * as Y from 'yjs'
|
||||
import { yXmlFragmentToProsemirrorJSON } from 'y-prosemirror'
|
||||
|
||||
const data = new URL('./data/', import.meta.url)
|
||||
|
||||
function unframe(buf) {
|
||||
const out = []
|
||||
for (let off = 0; off < buf.length; ) {
|
||||
const n = buf.readUInt32LE(off)
|
||||
out.push(buf.subarray(off + 4, off + 4 + n))
|
||||
off += 4 + n
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function time(fn) {
|
||||
const start = performance.now()
|
||||
const result = fn()
|
||||
return [result, Math.round(performance.now() - start)]
|
||||
}
|
||||
|
||||
for (const name of ['small', 'medium', 'large', 'concurrent']) {
|
||||
const updates = unframe(readFileSync(new URL(`${name}.updates`, data)))
|
||||
const want = JSON.parse(readFileSync(new URL(`${name}.json`, data), 'utf8'))
|
||||
const yrsSnapshot = readFileSync(new URL(`${name}.compact`, data))
|
||||
|
||||
const doc = new Y.Doc()
|
||||
Y.applyUpdate(doc, yrsSnapshot)
|
||||
const ok = isDeepStrictEqual(yXmlFragmentToProsemirrorJSON(doc.getXmlFragment('default')), want)
|
||||
|
||||
const [yjsSnapshot, compactMs] = time(() => {
|
||||
const d = new Y.Doc()
|
||||
d.transact(() => updates.forEach((u) => Y.applyUpdate(d, u)))
|
||||
return Y.encodeStateAsUpdate(d)
|
||||
})
|
||||
const identical = Buffer.compare(Buffer.from(yjsSnapshot), yrsSnapshot) === 0
|
||||
const [, jsonMs] = time(() => {
|
||||
const d = new Y.Doc()
|
||||
Y.applyUpdate(d, yjsSnapshot)
|
||||
return yXmlFragmentToProsemirrorJSON(d.getXmlFragment('default'))
|
||||
})
|
||||
let mergeMs = 'skipped'
|
||||
if (updates.length <= 50_000) [, mergeMs] = time(() => Y.mergeUpdates(updates))
|
||||
|
||||
console.log(
|
||||
`${name.padEnd(10)} yjs loads yrs snapshot: ${ok ? 'OK' : 'MISMATCH'}, byte-identical to yjs: ${identical}` +
|
||||
` | yjs compact ${compactMs} ms, json from snapshot ${jsonMs} ms, mergeUpdates ${mergeMs} ms`,
|
||||
)
|
||||
if (!ok) process.exitCode = 1
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
module docwell/spikes/yrswasm
|
||||
|
||||
go 1.26.4
|
||||
|
||||
require github.com/tetratelabs/wazero v1.12.0
|
||||
|
||||
require golang.org/x/sys v0.44.0 // indirect
|
||||
@@ -0,0 +1,4 @@
|
||||
github.com/tetratelabs/wazero v1.12.0 h1:DuWcpNu/FzgEXgGBDp8J1Spc+CWOvvtvVyjKlaZopYU=
|
||||
github.com/tetratelabs/wazero v1.12.0/go.mod h1:LvKtzl2RqO4gyF27BiXU+nKAjcV8f38U+kP/q2vgxh0=
|
||||
golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ=
|
||||
golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
@@ -0,0 +1,33 @@
|
||||
package yrs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestTiming reports one-shot wall times per operation (YRS_TIMING=1 to run).
|
||||
func TestTiming(t *testing.T) {
|
||||
if os.Getenv("YRS_TIMING") == "" {
|
||||
t.Skip("set YRS_TIMING=1")
|
||||
}
|
||||
ctx := context.Background()
|
||||
inst := newInstance(t)
|
||||
for _, name := range []string{"small", "medium", "concurrent"} {
|
||||
updates := load(t, name)
|
||||
for _, n := range []int{len(updates) / 4, len(updates) / 2, len(updates)} {
|
||||
u := updates[:n]
|
||||
s := time.Now()
|
||||
inst.JSON(ctx, u)
|
||||
j := time.Since(s)
|
||||
s = time.Now()
|
||||
inst.Merge(ctx, u)
|
||||
m := time.Since(s)
|
||||
s = time.Now()
|
||||
inst.Compact(ctx, u)
|
||||
c := time.Since(s)
|
||||
t.Logf("%-10s n=%6d json(apply) %8v merge %8v compact %8v", name, n, j.Round(time.Millisecond), m.Round(time.Millisecond), c.Round(time.Millisecond))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
// Package yrs runs yrs (the Rust Yjs port) compiled to WebAssembly under wazero,
|
||||
// so the Go server can merge, compact and read Yjs documents without cgo.
|
||||
//
|
||||
// A Runtime compiles the module once. An Instance is one sandboxed copy with its
|
||||
// own memory; it is not safe for concurrent use, so callers keep a pool.
|
||||
package yrs
|
||||
|
||||
import (
|
||||
"context"
|
||||
_ "embed"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/tetratelabs/wazero"
|
||||
"github.com/tetratelabs/wazero/api"
|
||||
"github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1"
|
||||
)
|
||||
|
||||
//go:embed docwell_yrs.wasm
|
||||
var wasm []byte
|
||||
|
||||
type Runtime struct {
|
||||
rt wazero.Runtime
|
||||
compiled wazero.CompiledModule
|
||||
}
|
||||
|
||||
// New compiles the embedded module. Compilation is the slow step, so do it once per process.
|
||||
func New(ctx context.Context) (*Runtime, error) {
|
||||
rt := wazero.NewRuntime(ctx)
|
||||
wasi_snapshot_preview1.MustInstantiate(ctx, rt)
|
||||
compiled, err := rt.CompileModule(ctx, wasm)
|
||||
if err != nil {
|
||||
rt.Close(ctx)
|
||||
return nil, fmt.Errorf("compile yrs.wasm: %w", err)
|
||||
}
|
||||
return &Runtime{rt: rt, compiled: compiled}, nil
|
||||
}
|
||||
|
||||
func (r *Runtime) Close(ctx context.Context) error { return r.rt.Close(ctx) }
|
||||
|
||||
type Instance struct {
|
||||
mod api.Module
|
||||
alloc, free, outPtr api.Function
|
||||
merge, compact, stateVector, diff, json, text api.Function
|
||||
}
|
||||
|
||||
// Instance creates a fresh module instance with its own linear memory.
|
||||
func (r *Runtime) Instance(ctx context.Context) (*Instance, error) {
|
||||
cfg := wazero.NewModuleConfig().WithName("").WithStartFunctions("_initialize")
|
||||
mod, err := r.rt.InstantiateModule(ctx, r.compiled, cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("instantiate yrs.wasm: %w", err)
|
||||
}
|
||||
return &Instance{
|
||||
mod: mod,
|
||||
alloc: mod.ExportedFunction("dw_alloc"),
|
||||
free: mod.ExportedFunction("dw_free"),
|
||||
outPtr: mod.ExportedFunction("dw_out_ptr"),
|
||||
merge: mod.ExportedFunction("dw_merge"),
|
||||
compact: mod.ExportedFunction("dw_compact"),
|
||||
stateVector: mod.ExportedFunction("dw_state_vector"),
|
||||
diff: mod.ExportedFunction("dw_diff"),
|
||||
json: mod.ExportedFunction("dw_to_json"),
|
||||
text: mod.ExportedFunction("dw_to_text"),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (i *Instance) Close(ctx context.Context) error { return i.mod.Close(ctx) }
|
||||
|
||||
// MemoryBytes is the instance's current linear memory size. WebAssembly memory never
|
||||
// shrinks, so a pool should retire instances that grew after a very large document.
|
||||
func (i *Instance) MemoryBytes() uint32 { return i.mod.Memory().Size() }
|
||||
|
||||
// Merge combines updates into one update without building a document. Deleted
|
||||
// content stays as tombstones; use Compact to drop it.
|
||||
func (i *Instance) Merge(ctx context.Context, updates [][]byte) ([]byte, error) {
|
||||
return i.call(ctx, i.merge, Frame(updates))
|
||||
}
|
||||
|
||||
// Compact applies updates to a document and returns its full state as one update.
|
||||
func (i *Instance) Compact(ctx context.Context, updates [][]byte) ([]byte, error) {
|
||||
return i.call(ctx, i.compact, Frame(updates))
|
||||
}
|
||||
|
||||
// StateVector returns the state vector encoded in an update.
|
||||
func (i *Instance) StateVector(ctx context.Context, update []byte) ([]byte, error) {
|
||||
return i.call(ctx, i.stateVector, update)
|
||||
}
|
||||
|
||||
// Diff returns what a peer with state vector sv is missing from update (sync step 2).
|
||||
func (i *Instance) Diff(ctx context.Context, update, sv []byte) ([]byte, error) {
|
||||
return i.call(ctx, i.diff, update, sv)
|
||||
}
|
||||
|
||||
// JSON returns the "default" XML fragment as ProseMirror JSON.
|
||||
func (i *Instance) JSON(ctx context.Context, updates [][]byte) ([]byte, error) {
|
||||
return i.call(ctx, i.json, Frame(updates))
|
||||
}
|
||||
|
||||
// Text returns the document's plain text, one line per block.
|
||||
func (i *Instance) Text(ctx context.Context, updates [][]byte) (string, error) {
|
||||
b, err := i.call(ctx, i.text, Frame(updates))
|
||||
return string(b), err
|
||||
}
|
||||
|
||||
// call copies each input into guest memory, runs fn(ptr, len, ...) and copies the result out.
|
||||
func (i *Instance) call(ctx context.Context, fn api.Function, inputs ...[]byte) ([]byte, error) {
|
||||
mem := i.mod.Memory()
|
||||
args := make([]uint64, 0, 2*len(inputs))
|
||||
for _, in := range inputs {
|
||||
res, err := i.alloc.Call(ctx, uint64(len(in)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ptr := uint32(res[0])
|
||||
defer i.free.Call(ctx, uint64(ptr), uint64(len(in)))
|
||||
if !mem.Write(ptr, in) {
|
||||
return nil, errors.New("yrs: write out of range")
|
||||
}
|
||||
args = append(args, uint64(ptr), uint64(len(in)))
|
||||
}
|
||||
res, err := fn.Call(ctx, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n := int32(res[0])
|
||||
ptrRes, err := i.outPtr.Call(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
failed := n < 0
|
||||
if failed {
|
||||
n = -n - 1 // the output buffer holds an n-byte error message
|
||||
}
|
||||
out, ok := mem.Read(uint32(ptrRes[0]), uint32(n))
|
||||
if !ok {
|
||||
return nil, errors.New("yrs: read out of range")
|
||||
}
|
||||
if failed {
|
||||
return nil, fmt.Errorf("yrs: %s", out)
|
||||
}
|
||||
return append([]byte(nil), out...), nil
|
||||
}
|
||||
|
||||
// Frame encodes updates as [u32 LE length][bytes] frames.
|
||||
func Frame(updates [][]byte) []byte {
|
||||
n := 0
|
||||
for _, u := range updates {
|
||||
n += 4 + len(u)
|
||||
}
|
||||
buf := make([]byte, 0, n)
|
||||
for _, u := range updates {
|
||||
buf = binary.LittleEndian.AppendUint32(buf, uint32(len(u)))
|
||||
buf = append(buf, u...)
|
||||
}
|
||||
return buf
|
||||
}
|
||||
|
||||
// Unframe splits a framed buffer back into updates.
|
||||
func Unframe(buf []byte) ([][]byte, error) {
|
||||
var out [][]byte
|
||||
for len(buf) > 0 {
|
||||
if len(buf) < 4 {
|
||||
return nil, errors.New("truncated frame header")
|
||||
}
|
||||
n := binary.LittleEndian.Uint32(buf)
|
||||
buf = buf[4:]
|
||||
if uint32(len(buf)) < n {
|
||||
return nil, errors.New("truncated frame")
|
||||
}
|
||||
out = append(out, buf[:n])
|
||||
buf = buf[n:]
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
package yrs
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var fixtures = []string{"small", "medium", "large", "concurrent"}
|
||||
|
||||
const dataDir = "../fixtures/data"
|
||||
|
||||
// maxMerge caps the logs passed to Merge, which is quadratic in the number of updates.
|
||||
const maxMerge = 50_000
|
||||
|
||||
func load(t testing.TB, name string) [][]byte {
|
||||
t.Helper()
|
||||
buf, err := os.ReadFile(filepath.Join(dataDir, name+".updates"))
|
||||
if err != nil {
|
||||
t.Fatalf("read fixture (run `node generate.mjs` in ../fixtures): %v", err)
|
||||
}
|
||||
updates, err := Unframe(buf)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return updates
|
||||
}
|
||||
|
||||
func expected(t testing.TB, name string) any {
|
||||
t.Helper()
|
||||
buf, err := os.ReadFile(filepath.Join(dataDir, name+".json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var v any
|
||||
if err := json.Unmarshal(buf, &v); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func newInstance(t testing.TB) *Instance {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
rt, err := New(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { rt.Close(ctx) })
|
||||
inst, err := rt.Instance(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return inst
|
||||
}
|
||||
|
||||
func assertJSON(t *testing.T, got []byte, want any) {
|
||||
t.Helper()
|
||||
var v any
|
||||
if err := json.Unmarshal(got, &v); err != nil {
|
||||
t.Fatalf("invalid JSON: %v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(v, want) {
|
||||
g, _ := json.Marshal(v)
|
||||
w, _ := json.Marshal(want)
|
||||
i := 0
|
||||
for i < len(g) && i < len(w) && g[i] == w[i] {
|
||||
i++
|
||||
}
|
||||
lo := max(0, i-80)
|
||||
t.Fatalf("JSON differs at byte %d\n got: …%s…\nwant: …%s…", i, g[lo:min(len(g), i+80)], w[lo:min(len(w), i+80)])
|
||||
}
|
||||
}
|
||||
|
||||
// TestMatchesYjs checks every path to a document against y-prosemirror's JSON:
|
||||
// the raw log, a merged update, a compacted update, and compaction in batches
|
||||
// the way the server would persist it.
|
||||
func TestMatchesYjs(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
inst := newInstance(t)
|
||||
for _, name := range fixtures {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
updates, want := load(t, name), expected(t, name)
|
||||
|
||||
got, err := inst.JSON(ctx, updates)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertJSON(t, got, want)
|
||||
|
||||
// merge_updates_v1 is quadratic in the number of updates (see ADR); skip the huge log.
|
||||
var merged []byte
|
||||
if len(updates) <= maxMerge {
|
||||
if merged, err = inst.Merge(ctx, updates); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err = inst.JSON(ctx, [][]byte{merged})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertJSON(t, got, want)
|
||||
}
|
||||
|
||||
compacted, err := inst.Compact(ctx, updates)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err = inst.JSON(ctx, [][]byte{compacted})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertJSON(t, got, want)
|
||||
// For verify.mjs: yjs must load what yrs wrote.
|
||||
os.WriteFile(filepath.Join(dataDir, name+".compact"), compacted, 0o644)
|
||||
|
||||
// Server-style: snapshot + the next 500 updates, repeatedly.
|
||||
var snapshot []byte
|
||||
for start := 0; start < len(updates); start += 500 {
|
||||
batch := updates[start:min(start+500, len(updates))]
|
||||
if snapshot != nil {
|
||||
batch = append([][]byte{snapshot}, batch...)
|
||||
}
|
||||
if snapshot, err = inst.Compact(ctx, batch); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
got, _ = inst.JSON(ctx, [][]byte{snapshot})
|
||||
assertJSON(t, got, want)
|
||||
|
||||
t.Logf("%d updates, log %d B → merged %d B, compacted %d B, memory %d MiB",
|
||||
len(updates), len(Frame(updates)), len(merged), len(compacted), inst.MemoryBytes()>>20)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiffSync(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
inst := newInstance(t)
|
||||
updates := load(t, "medium")
|
||||
half := len(updates) / 2
|
||||
|
||||
server, _ := inst.Compact(ctx, updates)
|
||||
client, _ := inst.Compact(ctx, updates[:half])
|
||||
sv, err := inst.StateVector(ctx, client)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
missing, err := inst.Diff(ctx, server, sv)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(missing) >= len(server) {
|
||||
t.Fatalf("diff %d B is not smaller than full state %d B", len(missing), len(server))
|
||||
}
|
||||
got, _ := inst.JSON(ctx, [][]byte{client, missing})
|
||||
assertJSON(t, got, expected(t, "medium"))
|
||||
}
|
||||
|
||||
func TestText(t *testing.T) {
|
||||
inst := newInstance(t)
|
||||
text, err := inst.Text(context.Background(), load(t, "small"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(text, "żółć") || strings.Count(text, "\n") < 10 {
|
||||
t.Fatalf("unexpected text: %.200q", text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadInput(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
inst := newInstance(t)
|
||||
for _, in := range [][]byte{{0xff, 0xff, 0xff}, bytes.Repeat([]byte{7}, 64), {}} {
|
||||
if _, err := inst.Compact(ctx, [][]byte{in}); err != nil {
|
||||
t.Logf("rejected %x: %v", in[:min(len(in), 4)], err)
|
||||
}
|
||||
}
|
||||
// The instance must still work after rejecting garbage.
|
||||
got, err := inst.JSON(ctx, load(t, "small"))
|
||||
if err != nil {
|
||||
t.Fatalf("instance unusable after bad input: %v", err)
|
||||
}
|
||||
assertJSON(t, got, expected(t, "small"))
|
||||
}
|
||||
|
||||
// TestConcurrent runs one instance per goroutine, sharing one compiled module.
|
||||
func TestConcurrent(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
rt, err := New(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer rt.Close(ctx)
|
||||
updates, want := load(t, "medium"), expected(t, "medium")
|
||||
var wg sync.WaitGroup
|
||||
errs := make(chan error, 8)
|
||||
for range 8 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
inst, err := rt.Instance(ctx)
|
||||
if err != nil {
|
||||
errs <- err
|
||||
return
|
||||
}
|
||||
defer inst.Close(ctx)
|
||||
got, err := inst.JSON(ctx, updates)
|
||||
if err != nil {
|
||||
errs <- err
|
||||
return
|
||||
}
|
||||
var v any
|
||||
json.Unmarshal(got, &v)
|
||||
if !reflect.DeepEqual(v, want) {
|
||||
errs <- fmt.Errorf("mismatch")
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartupCost(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
start := time.Now()
|
||||
rt, err := New(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer rt.Close(ctx)
|
||||
compiled := time.Since(start)
|
||||
start = time.Now()
|
||||
inst, err := rt.Instance(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Logf("compile %v, instantiate %v, wasm %d KiB, initial memory %d KiB",
|
||||
compiled, time.Since(start), len(wasm)>>10, inst.MemoryBytes()>>10)
|
||||
}
|
||||
|
||||
func bench(b *testing.B, op func(*Instance, context.Context, [][]byte) error) {
|
||||
ctx := context.Background()
|
||||
inst := newInstance(b)
|
||||
for _, name := range fixtures {
|
||||
updates := load(b, name)
|
||||
b.Run(name, func(b *testing.B) {
|
||||
b.SetBytes(int64(len(Frame(updates))))
|
||||
for b.Loop() {
|
||||
if err := op(inst, ctx, updates); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkMerge(b *testing.B) {
|
||||
bench(b, func(i *Instance, ctx context.Context, u [][]byte) error {
|
||||
if len(u) > maxMerge {
|
||||
b.Skip("quadratic; see TestTiming")
|
||||
}
|
||||
_, err := i.Merge(ctx, u)
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
func BenchmarkCompact(b *testing.B) {
|
||||
bench(b, func(i *Instance, ctx context.Context, u [][]byte) error { _, err := i.Compact(ctx, u); return err })
|
||||
}
|
||||
|
||||
// BenchmarkJSONFromSnapshot is the export / search-indexing path: one stored snapshot to JSON.
|
||||
func BenchmarkJSONFromSnapshot(b *testing.B) {
|
||||
ctx := context.Background()
|
||||
inst := newInstance(b)
|
||||
for _, name := range fixtures {
|
||||
snap, err := inst.Compact(ctx, load(b, name))
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
b.Run(name, func(b *testing.B) {
|
||||
for b.Loop() {
|
||||
if _, err := inst.JSON(ctx, [][]byte{snap}); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkTextFromSnapshot(b *testing.B) {
|
||||
ctx := context.Background()
|
||||
inst := newInstance(b)
|
||||
for _, name := range fixtures {
|
||||
snap, _ := inst.Compact(ctx, load(b, name))
|
||||
b.Run(name, func(b *testing.B) {
|
||||
for b.Loop() {
|
||||
if _, err := inst.Text(ctx, [][]byte{snap}); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkCompactIncremental is the steady-state server job: snapshot + 200 new updates → new snapshot.
|
||||
func BenchmarkCompactIncremental(b *testing.B) {
|
||||
ctx := context.Background()
|
||||
inst := newInstance(b)
|
||||
for _, name := range fixtures {
|
||||
updates := load(b, name)
|
||||
cut := len(updates) - 200
|
||||
snap, _ := inst.Compact(ctx, updates[:cut])
|
||||
batch := append([][]byte{snap}, updates[cut:]...)
|
||||
b.Run(name, func(b *testing.B) {
|
||||
for b.Loop() {
|
||||
if _, err := inst.Compact(ctx, batch); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkInstantiate(b *testing.B) {
|
||||
ctx := context.Background()
|
||||
rt, err := New(ctx)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
defer rt.Close(ctx)
|
||||
for b.Loop() {
|
||||
inst, err := rt.Instance(ctx)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
inst.Close(ctx)
|
||||
}
|
||||
}
|
||||
Generated
+410
@@ -0,0 +1,410 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "arc-swap"
|
||||
version = "1.9.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "380962b3d93b99642e50b9febf72c071e97e8b32d86eae9cf4ef582bb960ae6e"
|
||||
dependencies = [
|
||||
"rustversion",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-lock"
|
||||
version = "3.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311"
|
||||
dependencies = [
|
||||
"event-listener",
|
||||
"event-listener-strategy",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-trait"
|
||||
version = "0.1.92"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.20.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-utils"
|
||||
version = "0.8.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
|
||||
|
||||
[[package]]
|
||||
name = "dashmap"
|
||||
version = "6.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"crossbeam-utils",
|
||||
"hashbrown",
|
||||
"lock_api",
|
||||
"once_cell",
|
||||
"parking_lot_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "docwell_yrs"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
"yrs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "event-listener"
|
||||
version = "5.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2"
|
||||
dependencies = [
|
||||
"parking",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "event-listener-strategy"
|
||||
version = "0.5.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"
|
||||
dependencies = [
|
||||
"event-listener",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
|
||||
dependencies = [
|
||||
"getrandom",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"r-efi",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.14.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||
|
||||
[[package]]
|
||||
name = "lock_api"
|
||||
version = "0.4.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
|
||||
dependencies = [
|
||||
"scopeguard",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "parking"
|
||||
version = "2.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot_core"
|
||||
version = "0.9.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"redox_syscall",
|
||||
"smallvec",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "r-efi"
|
||||
version = "6.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
||||
|
||||
[[package]]
|
||||
name = "redox_syscall"
|
||||
version = "0.5.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustversion"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
||||
|
||||
[[package]]
|
||||
name = "scopeguard"
|
||||
version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.154"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_core",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "smallstr"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "862077b1e764f04c251fe82a2ef562fd78d7cadaeb072ca7c2bcaf7217b1ff3b"
|
||||
dependencies = [
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "smallvec"
|
||||
version = "1.16.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "2.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
|
||||
dependencies = [
|
||||
"thiserror-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "2.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen"
|
||||
version = "0.2.130"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"rustversion",
|
||||
"wasm-bindgen-macro",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-macro"
|
||||
version = "0.2.130"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"wasm-bindgen-macro-support",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-macro-support"
|
||||
version = "0.2.130"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a"
|
||||
dependencies = [
|
||||
"bumpalo",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-shared"
|
||||
version = "0.2.130"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "yrs"
|
||||
version = "0.28.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "52c70dc8beca8666c77612a96889106ca3cd65318609721f464624ff79685da9"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"async-lock",
|
||||
"async-trait",
|
||||
"dashmap",
|
||||
"fastrand",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"smallstr",
|
||||
"smallvec",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "docwell_yrs"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
license = "AGPL-3.0-or-later"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
serde_json = "1.0.154"
|
||||
yrs = "0.28"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[profile.release]
|
||||
opt-level = 3
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
panic = "abort"
|
||||
strip = true
|
||||
@@ -0,0 +1,23 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
//! Times the same operations natively, to measure what WebAssembly costs.
|
||||
//! cargo run --release --example native -- ../fixtures/data/medium.updates
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use docwell_yrs::{dw_compact, dw_to_json};
|
||||
|
||||
fn main() {
|
||||
for path in std::env::args().skip(1) {
|
||||
let log = std::fs::read(&path).unwrap();
|
||||
let t = Instant::now();
|
||||
let n = unsafe { dw_compact(log.as_ptr(), log.len() as u32) };
|
||||
let compact = t.elapsed();
|
||||
let snap = unsafe { std::slice::from_raw_parts(docwell_yrs::dw_out_ptr(), n as usize) }.to_vec();
|
||||
let mut framed = (snap.len() as u32).to_le_bytes().to_vec();
|
||||
framed.extend_from_slice(&snap);
|
||||
let t = Instant::now();
|
||||
unsafe { dw_to_json(framed.as_ptr(), framed.len() as u32) };
|
||||
println!("{path}: compact {:?}, json from snapshot {:?}", compact, t.elapsed());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
//! yrs compiled to wasm32-wasip1 for the Go server (ADR-3 spike).
|
||||
//!
|
||||
//! ABI: the host allocates input with `dw_alloc`, calls an operation, and on
|
||||
//! success (return >= 0) reads that many bytes from `dw_out_ptr()`. A negative
|
||||
//! return `-(n + 1)` means an error whose n-byte message is in the output buffer. Several
|
||||
//! updates are passed as one buffer of `[u32 little-endian length][bytes]` frames.
|
||||
|
||||
use std::cell::RefCell;
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
use yrs::types::text::{Diff, YChange};
|
||||
use yrs::updates::decoder::Decode;
|
||||
use yrs::{
|
||||
Any, Doc, GetString, Out, ReadTxn, StateVector, Text, Transact, Update, Xml, XmlFragment,
|
||||
XmlOut,
|
||||
};
|
||||
|
||||
/// Tiptap's Collaboration extension stores the document in this fragment.
|
||||
const FRAGMENT: &str = "default";
|
||||
|
||||
thread_local! {
|
||||
static OUT: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
fn finish(result: Result<Vec<u8>, String>) -> i32 {
|
||||
OUT.with(|out| {
|
||||
let mut out = out.borrow_mut();
|
||||
match result {
|
||||
Ok(bytes) => {
|
||||
*out = bytes;
|
||||
out.len() as i32
|
||||
}
|
||||
Err(msg) => {
|
||||
*out = msg.into_bytes();
|
||||
-(out.len() as i32) - 1
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
unsafe fn input<'a>(ptr: *const u8, len: u32) -> &'a [u8] {
|
||||
if len == 0 {
|
||||
&[]
|
||||
} else {
|
||||
std::slice::from_raw_parts(ptr, len as usize)
|
||||
}
|
||||
}
|
||||
|
||||
fn frames(mut buf: &[u8]) -> Result<Vec<&[u8]>, String> {
|
||||
let mut out = Vec::new();
|
||||
while !buf.is_empty() {
|
||||
if buf.len() < 4 {
|
||||
return Err("truncated frame header".into());
|
||||
}
|
||||
let n = u32::from_le_bytes(buf[..4].try_into().unwrap()) as usize;
|
||||
buf = &buf[4..];
|
||||
if buf.len() < n {
|
||||
return Err("truncated frame".into());
|
||||
}
|
||||
out.push(&buf[..n]);
|
||||
buf = &buf[n..];
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn load(updates: &[&[u8]]) -> Result<Doc, String> {
|
||||
let doc = Doc::new();
|
||||
{
|
||||
let mut txn = doc.transact_mut();
|
||||
for u in updates {
|
||||
let update = Update::decode_v1(u).map_err(|e| e.to_string())?;
|
||||
txn.apply_update(update).map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn dw_alloc(len: u32) -> *mut u8 {
|
||||
let mut buf = Vec::<u8>::with_capacity(len as usize);
|
||||
let ptr = buf.as_mut_ptr();
|
||||
std::mem::forget(buf);
|
||||
ptr
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn dw_free(ptr: *mut u8, len: u32) {
|
||||
drop(Vec::from_raw_parts(ptr, 0, len as usize));
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn dw_out_ptr() -> *const u8 {
|
||||
OUT.with(|out| out.borrow().as_ptr())
|
||||
}
|
||||
|
||||
/// Merges framed updates into one without building a document (cheap, keeps tombstones).
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn dw_merge(ptr: *const u8, len: u32) -> i32 {
|
||||
finish(frames(input(ptr, len)).and_then(|f| yrs::merge_updates_v1(f).map_err(|e| e.to_string())))
|
||||
}
|
||||
|
||||
/// Applies framed updates to a document and re-encodes its full state (garbage-collects deleted content).
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn dw_compact(ptr: *const u8, len: u32) -> i32 {
|
||||
finish(frames(input(ptr, len)).and_then(|f| {
|
||||
let doc = load(&f)?;
|
||||
let txn = doc.transact();
|
||||
Ok(txn.encode_state_as_update_v1(&StateVector::default()))
|
||||
}))
|
||||
}
|
||||
|
||||
/// Encodes the state vector of an update.
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn dw_state_vector(ptr: *const u8, len: u32) -> i32 {
|
||||
finish(yrs::encode_state_vector_from_update_v1(input(ptr, len)).map_err(|e| e.to_string()))
|
||||
}
|
||||
|
||||
/// Returns the part of an update that a peer with the given state vector is missing.
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn dw_diff(ptr: *const u8, len: u32, sv_ptr: *const u8, sv_len: u32) -> i32 {
|
||||
finish(yrs::diff_updates_v1(input(ptr, len), input(sv_ptr, sv_len)).map_err(|e| e.to_string()))
|
||||
}
|
||||
|
||||
/// Converts framed updates to ProseMirror JSON, matching y-prosemirror's `yXmlFragmentToProsemirrorJSON`.
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn dw_to_json(ptr: *const u8, len: u32) -> i32 {
|
||||
finish(frames(input(ptr, len)).and_then(|f| {
|
||||
let doc = load(&f)?;
|
||||
let fragment = doc.get_or_insert_xml_fragment(FRAGMENT);
|
||||
let txn = doc.transact();
|
||||
let content: Vec<Value> = fragment.children(&txn).flat_map(|n| node_json(&txn, n)).collect();
|
||||
let mut root = Map::new();
|
||||
root.insert("type".into(), "doc".into());
|
||||
root.insert("content".into(), content.into());
|
||||
serde_json::to_vec(&Value::Object(root)).map_err(|e| e.to_string())
|
||||
}))
|
||||
}
|
||||
|
||||
/// Extracts plain text for search: one line per block.
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn dw_to_text(ptr: *const u8, len: u32) -> i32 {
|
||||
finish(frames(input(ptr, len)).and_then(|f| {
|
||||
let doc = load(&f)?;
|
||||
let fragment = doc.get_or_insert_xml_fragment(FRAGMENT);
|
||||
let txn = doc.transact();
|
||||
let mut text = String::new();
|
||||
for node in fragment.children(&txn) {
|
||||
node_text(&txn, node, &mut text);
|
||||
text.push('\n');
|
||||
}
|
||||
Ok(text.into_bytes())
|
||||
}))
|
||||
}
|
||||
|
||||
fn node_json<T: ReadTxn>(txn: &T, node: XmlOut) -> Vec<Value> {
|
||||
match node {
|
||||
XmlOut::Text(t) => t
|
||||
.diff(txn, YChange::identity)
|
||||
.into_iter()
|
||||
.map(|d| text_json(txn, d))
|
||||
.collect(),
|
||||
XmlOut::Element(e) => {
|
||||
let mut obj = Map::new();
|
||||
obj.insert("type".into(), e.tag().to_string().into());
|
||||
let attrs: Map<String, Value> =
|
||||
e.attributes(txn).map(|(k, v)| (k.to_string(), out_json(txn, v))).collect();
|
||||
if !attrs.is_empty() {
|
||||
obj.insert("attrs".into(), attrs.into());
|
||||
}
|
||||
// y-prosemirror writes `content` whenever there are children, even if they are empty text.
|
||||
if e.first_child().is_some() {
|
||||
let content: Vec<Value> = e.children(txn).flat_map(|n| node_json(txn, n)).collect();
|
||||
obj.insert("content".into(), content.into());
|
||||
}
|
||||
vec![Value::Object(obj)]
|
||||
}
|
||||
XmlOut::Fragment(f) => f.children(txn).flat_map(|n| node_json(txn, n)).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn text_json<T: ReadTxn>(txn: &T, d: Diff<YChange>) -> Value {
|
||||
let mut obj = Map::new();
|
||||
obj.insert("type".into(), "text".into());
|
||||
obj.insert("text".into(), out_json(txn, d.insert));
|
||||
if let Some(attrs) = d.attributes {
|
||||
let marks: Vec<Value> = attrs
|
||||
.iter()
|
||||
.map(|(name, value)| {
|
||||
let mut mark = Map::new();
|
||||
mark.insert("type".into(), name.to_string().into());
|
||||
// y-prosemirror always writes attrs, even when empty.
|
||||
let attrs = match any_json(value) {
|
||||
Value::Object(m) => Value::Object(m),
|
||||
_ => Value::Object(Map::new()),
|
||||
};
|
||||
mark.insert("attrs".into(), attrs);
|
||||
Value::Object(mark)
|
||||
})
|
||||
.collect();
|
||||
obj.insert("marks".into(), marks.into());
|
||||
}
|
||||
Value::Object(obj)
|
||||
}
|
||||
|
||||
fn node_text<T: ReadTxn>(txn: &T, node: XmlOut, buf: &mut String) {
|
||||
match node {
|
||||
XmlOut::Text(t) => buf.push_str(&t.get_string(txn)),
|
||||
XmlOut::Element(e) => {
|
||||
for (i, child) in e.children(txn).enumerate() {
|
||||
if i > 0 && matches!(child, XmlOut::Element(_)) {
|
||||
buf.push('\n');
|
||||
}
|
||||
node_text(txn, child, buf);
|
||||
}
|
||||
}
|
||||
XmlOut::Fragment(f) => f.children(txn).for_each(|c| node_text(txn, c, buf)),
|
||||
}
|
||||
}
|
||||
|
||||
fn out_json<T: ReadTxn>(txn: &T, out: Out) -> Value {
|
||||
match out {
|
||||
Out::Any(a) => any_json(&a),
|
||||
Out::YXmlText(t) => t.get_string(txn).into(),
|
||||
other => other.to_string(txn).into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn any_json(any: &Any) -> Value {
|
||||
match any {
|
||||
Any::Null | Any::Undefined => Value::Null,
|
||||
Any::Bool(b) => (*b).into(),
|
||||
Any::Number(yrs::Number::Int(i)) => (*i).into(),
|
||||
Any::Number(yrs::Number::Float(f)) => serde_json::Number::from_f64(*f).map_or(Value::Null, Value::Number),
|
||||
Any::String(s) => s.to_string().into(),
|
||||
Any::Buffer(b) => b.iter().copied().map(Value::from).collect(),
|
||||
Any::Array(a) => a.iter().map(any_json).collect(),
|
||||
Any::Map(m) => Value::Object(m.iter().map(|(k, v)| (k.clone(), any_json(v))).collect()),
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -47,7 +47,7 @@ Docwell is an open-source, self-hostable knowledge base and collaborative docume
|
||||
|---|---|---|
|
||||
| ADR-1 | **Editor = Tiptap 2/3 (ProseMirror) for web and desktop**, with `@tiptap/vue-3` | This is the stack Docmost uses and close to what Outline uses. It has a large extension ecosystem (tables, math, mentions, collaboration) and is MIT licensed. |
|
||||
| ADR-2 | **CRDT = Yjs** (`y-prosemirror`, `y-indexeddb`, Awareness for cursors) | Industry standard, and both Docmost and Outline use it. |
|
||||
| ADR-3 | **The Go server relays the y-websocket / Hocuspocus-compatible protocol** and stores incremental updates. Compaction (merging updates into a snapshot, and extracting plain text and JSON for search and exports) runs **Yrs compiled to WASM inside Go via `wazero`**, so there is no cgo and no Node sidecar. | There is no mature pure-Go Yjs port. Options considered: (a) a Node Hocuspocus sidecar, which breaks the "Go only" goal; (b) cgo + yffi, which complicates cross-compiling; (c) client-side compaction, which you can't trust. **(d) wazero + yrs.wasm** was chosen. Spike it in Phase 0. |
|
||||
| ADR-3 | **The Go server relays the y-websocket / Hocuspocus-compatible protocol** and stores incremental updates. Compaction (merging updates into a snapshot, and extracting plain text and JSON for search and exports) runs **Yrs compiled to WASM inside Go via `wazero`**, so there is no cgo and no Node sidecar. | There is no mature pure-Go Yjs port. Options considered: (a) a Node Hocuspocus sidecar, which breaks the "Go only" goal; (b) cgo + yffi, which complicates cross-compiling; (c) client-side compaction, which you can't trust. **(d) wazero + yrs.wasm** was chosen — **spike passed** ([ADR-3](adr/0003-yrs-wasm-wazero.md)): output matches y-prosemirror, steady-state compaction takes milliseconds, WebAssembly costs ≤2× native. Compact incrementally (snapshot + new updates); never `merge_updates` on long logs, which is quadratic. |
|
||||
| ADR-4 | **Mobile editor = the same Tiptap editor bundle running inside a Flutter WebView** (`webview_flutter` or `flutter_inappwebview`), bridged over JS channels. Navigation, lists, search, settings and comments are native Flutter. | Writing a second rich-text engine in Dart with identical schema and Yjs semantics is months of work and a constant source of divergence. AppFlowy built its own Flutter editor, but its data model is native to that editor. Revisit a native Dart editor in v2+. |
|
||||
| ADR-5 | **Search = Bleve** (pure Go, embedded in the server) with an optional **Meilisearch** adapter | PocketBase does not expose SQLite FTS5 through its API. Bleve keeps the "no extra service" promise. The search code sits behind an interface so you can swap the backend. |
|
||||
| ADR-6 | **Authentication = PocketBase's built-in `users` auth collection** — **decided**. PocketBase stores the credentials and issues the tokens, and also handles password, OTP email codes, MFA, OAuth2, verification and password-reset emails (via its own SMTP settings). PocketBase stays private: clients call `/api/v1/auth/*` on docwell-server, which forwards to PocketBase. The server checks bearer tokens through a small hook route (`pb_hooks/docwell.pb.js`, cached 30 s) and adds Docwell's rules: signup policy and domain allow-list, `status = disabled` blocks sign-in (PocketBase `authRule`), and the first account becomes the superadmin (see ADR-12). **Authorization** (workspace, space and page permissions) stays in docwell-server. | Less security-critical code to write and maintain, and auth features (MFA, OTP, OAuth2) come out of the box. Trade-offs: tokens are PocketBase JWTs, so sign-out is client-side (to revoke every session, rotate the user's `tokenKey`), and swapping PocketBase for Postgres later would need a token migration plan. |
|
||||
@@ -221,5 +221,5 @@ Time estimates assume ~2 full-time developers. Scale them for your team.
|
||||
|
||||
1. ~~Confirm the license and the Wails version~~ — decided: AGPL-3.0 for everything, Wails v3. Add the official AGPL-3.0 `LICENSE` text and SPDX headers (`AGPL-3.0-only` or `-or-later`) during scaffolding.
|
||||
2. Scaffold the monorepo (Phase 0 layout above) and docker-compose with the three services.
|
||||
3. Run the three Phase 0 spikes and record the results as ADRs in `docs/adr/`.
|
||||
3. Run the three Phase 0 spikes and record the results as ADRs in `docs/adr/`. Done: yrs.wasm under wazero ([ADR-3](adr/0003-yrs-wasm-wazero.md), go). Still to do: Tiptap in a Flutter WebView, Wails v3 tray/deep link/auto-update.
|
||||
4. Write `api/openapi.yaml` v0 and the first PocketBase migrations.
|
||||
@@ -0,0 +1,65 @@
|
||||
# ADR-3: Yjs compaction with yrs compiled to WebAssembly, run by wazero
|
||||
|
||||
- Status: **accepted** (Phase 0 spike passed, 2026-10-30)
|
||||
- Spike code: [`Spikes/yrs-wasm/`](../../Spikes/yrs-wasm/README.md)
|
||||
|
||||
## Context
|
||||
|
||||
The Go server relays Yjs updates between editors and stores them. It also has to read the documents itself: compact the update log into a snapshot, extract ProseMirror JSON for exports and plain text for search, and answer sync step 2 (send a peer what its state vector is missing). There is no mature pure-Go Yjs port. We wanted to avoid a Node sidecar and cgo, so the plan was to compile yrs (the Rust port of Yjs) to WebAssembly and run it in-process with wazero. This spike decides go or no-go.
|
||||
|
||||
## What was built
|
||||
|
||||
- `rust/`: a ~250-line wrapper around yrs 0.28 compiled to `wasm32-wasip1` (577 KiB). It exports `compact`, `merge`, `state_vector`, `diff`, `to_json` and `to_text` through a tiny pointer-and-length ABI.
|
||||
- `go/`: a wazero host (`yrs.go`) that embeds the module, plus tests and benchmarks.
|
||||
- `fixtures/`: generates realistic edit logs with real Yjs (keystroke-by-keystroke typing with headings, lists, bold and links, backspaces and edits to earlier blocks, and three clients editing concurrently). y-prosemirror's `yXmlFragmentToProsemirrorJSON` supplies the expected output. `verify.mjs` checks that Yjs loads what yrs wrote and times Yjs as a baseline.
|
||||
|
||||
| Fixture | Updates | Log size | Snapshot | Notes |
|
||||
|---|---:|---:|---:|---|
|
||||
| small | 2,277 | 56 KB | 5 KB | ~2k characters |
|
||||
| medium | 30,804 | 785 KB | 66 KB | ~30k characters, a long page |
|
||||
| large | 255,566 | 6.8 MB | 553 KB | ~250k characters, a book-length page |
|
||||
| concurrent | 19,999 | 697 KB | 597 KB | 3 clients, random sync order |
|
||||
|
||||
## Results
|
||||
|
||||
**Correctness: all pass.**
|
||||
- yrs JSON matches y-prosemirror exactly on every fixture. This holds whether yrs reads the raw log, a merged update, a compacted snapshot, or a snapshot rebuilt in batches of 500 updates (the server's real pattern).
|
||||
- Yjs loads every yrs snapshot and produces identical JSON. Snapshots are the same size as Yjs's own but not byte-identical, because encoding order differs. That doesn't matter.
|
||||
- Sync step 2 (`diff` against a client's state vector) brings a half-synced client to the same document.
|
||||
- Malformed updates return an error message, and the instance keeps working afterwards.
|
||||
- 8 goroutines, each with its own instance of one compiled module, run concurrently without problems.
|
||||
|
||||
**Speed** (AMD Threadripper 2950X, Go 1.26, wazero 1.12 compiler mode):
|
||||
|
||||
| Operation | small | medium | large | concurrent |
|
||||
|---|---:|---:|---:|---:|
|
||||
| Compact the full log (one-off) | 4.4 ms | 71 ms | 2.7 s | 80 ms |
|
||||
| **Compact snapshot + 200 new updates (steady state)** | **0.6 ms** | **2.9 ms** | **23 ms** | **47 ms** |
|
||||
| JSON from snapshot (export, indexing) | 0.3 ms | 3.5 ms | 33 ms | 42 ms |
|
||||
| Plain text from snapshot (search) | 0.25 ms | 2.6 ms | 23 ms | 39 ms |
|
||||
| `merge_updates_v1` on the full log | 67 ms | **13.2 s** | not run | **5.7 s** |
|
||||
|
||||
Baselines for the same machine and fixtures:
|
||||
- Native yrs (no WebAssembly) compacts in 2.7 / 38 / 2,500 / 49 ms and builds JSON in 0.27 / 2.9 / 32 / 32 ms. WebAssembly costs 1.0–1.9×, and the large case is limited by yrs itself.
|
||||
- Yjs in Node compacts in 20 / 103 / 1,468 / 166 ms, so yrs is in the same range. Its `mergeUpdates` is quadratic too (21.7 s on medium).
|
||||
|
||||
**Startup and memory:**
|
||||
- Compiling the module takes ~350 ms, once per process. Each instance takes 0.5 ms and 1.1 MiB to create.
|
||||
- Memory grows with the largest document an instance has loaded: 17 MiB after medium, 55 MiB after large. WebAssembly memory never shrinks.
|
||||
|
||||
## Decision
|
||||
|
||||
**Go.** Keep ADR-3 as planned: yrs.wasm under wazero, with no cgo and no Node sidecar. The rules below come from the spike.
|
||||
|
||||
1. **Compact incrementally; never use `merge` on long logs.** `merge_updates_v1` (and Yjs's `mergeUpdates`) is quadratic in the number of updates. The compaction job loads the latest snapshot plus the pending updates, applies them to a document and re-encodes it (`Compact`). That keeps the steady-state cost to milliseconds even for very long pages. Run it after N updates or T seconds of idle time per document.
|
||||
2. **One instance per worker, with a pool.** Instances aren't safe for concurrent use. Compile once at startup. Retire an instance when its memory passes a limit (start at 64 MiB) and **after any error that came from a trap**, because the module is built with `panic = "abort"`.
|
||||
3. **Reuse the startup cost.** Turn on wazero's file compilation cache so restarts skip most of the 350 ms compile.
|
||||
4. **Text offsets are UTF-16, as in Yjs.** When an edit splits a surrogate pair (an emoji), Yjs keeps the broken half or replaces it with U+FFFD, and yrs keeps the character whole. ProseMirror never splits a surrogate pair, so real editors don't hit this. Our own code must never produce such edits either: no server-side text edits at raw offsets.
|
||||
5. **Build:** pin `yrs` (0.28.x) and build the module in CI and the Docker images with the `wasm32-wasip1` target, then embed it with `go:embed`. Don't commit the binary. yrs is MIT licensed, which is compatible with AGPL-3.0.
|
||||
6. **Platforms:** wazero's compiler covers amd64 and arm64, which are the published image architectures. Other architectures fall back to wazero's interpreter, which is much slower; that's acceptable for hobby use but not supported.
|
||||
|
||||
## Not covered (follow up in Phase 1)
|
||||
|
||||
- Tiptap extensions beyond StarterKit, links and headings (tables, mentions, images). The JSON conversion is generic over element names and attributes, so they should work, but test them against the real editor schema.
|
||||
- Subdocuments, and the awareness protocol (cursors). The awareness protocol is relayed without decoding, so it doesn't need yrs.
|
||||
- Long-running memory behaviour under a real workload, and the pool's retirement threshold.
|
||||
Reference in new issue
Block a user