Files
Docwell/Server/ycrdt-wasm/src/lib.rs
T
tajniak81andClaude Opus 5.5 5e1dcf4291 Add real-time collaboration with page history
Pages are now shared Yjs documents. docwell-server relays the y-websocket
protocol at /collab (token sent as the first message), flushes updates to
page_yupdates every second, and compacts them into page_ydoc with yrs
compiled to WebAssembly under wazero (ADR-3) after 30 s idle or when the
last editor leaves. Compaction refreshes content_json/content_text and
records page_versions; versions can be listed, previewed and restored.

The editor connects through a small y-protocols provider with carets and
presence. Pages saved before this change are seeded from content_json.
The yrs module lives in Server/ycrdt-wasm and is built by go generate,
CI and the Dockerfiles rather than committed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 11:52:55 +01:00

330 lines
12 KiB
Rust

// SPDX-License-Identifier: AGPL-3.0-or-later
//! yrs compiled to wasm32-wasip1 for the Go server (ADR-3), embedded by
//! Server/internal/ycrdt.
//!
//! 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::types::Attrs;
use yrs::{
Any, Doc, GetString, Out, ReadTxn, StateVector, Text, Transact, TransactionMut, Update, Xml,
XmlElementPrelim, XmlFragment, XmlOut, XmlTextPrelim,
};
/// 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())
}))
}
/// Replaces the document in the framed updates with ProseMirror JSON (input 2)
/// and returns the change as one incremental update, written the way
/// y-prosemirror's `prosemirrorToYXmlFragment` would.
#[no_mangle]
pub unsafe extern "C" fn dw_replace(ptr: *const u8, len: u32, json_ptr: *const u8, json_len: u32) -> i32 {
finish(frames(input(ptr, len)).and_then(|f| {
let root: Value = serde_json::from_slice(input(json_ptr, json_len)).map_err(|e| e.to_string())?;
if root.get("type").and_then(Value::as_str) != Some("doc") {
return Err("not a ProseMirror doc".into());
}
let content = match root.get("content") {
Some(Value::Array(c)) => c.as_slice(),
_ => &[],
};
let doc = load(&f)?;
let fragment = doc.get_or_insert_xml_fragment(FRAGMENT);
let before = doc.transact().state_vector();
{
let mut txn = doc.transact_mut();
let n = fragment.len(&txn);
fragment.remove_range(&mut txn, 0, n);
fill(&mut txn, &fragment, content, 0)?;
}
let txn = doc.transact();
Ok(txn.encode_state_as_update_v1(&before))
}))
}
/// Appends ProseMirror nodes to parent. Runs of text nodes become one XmlText
/// whose formatting attributes are the marks, as in y-prosemirror.
fn fill<P: XmlFragment>(txn: &mut TransactionMut, parent: &P, nodes: &[Value], depth: u32) -> Result<(), String> {
if depth > 200 {
return Err("document is nested too deeply".into());
}
let node_type = |n: &Value| n.get("type").and_then(Value::as_str).map(str::to_owned);
let mut i = 0;
while i < nodes.len() {
let ty = node_type(&nodes[i]).ok_or("node without a type")?;
let index = parent.len(txn);
if ty == "text" {
let text = parent.insert(txn, index, XmlTextPrelim::new(""));
while i < nodes.len() && node_type(&nodes[i]).as_deref() == Some("text") {
let chunk = nodes[i].get("text").and_then(Value::as_str).unwrap_or("");
let mut attrs = Attrs::new();
if let Some(Value::Array(marks)) = nodes[i].get("marks") {
for mark in marks {
let name = mark.get("type").and_then(Value::as_str).ok_or("mark without a type")?;
let value = mark.get("attrs").cloned().unwrap_or_else(|| Value::Object(Map::new()));
attrs.insert(name.into(), json_any(value)?);
}
}
let at = text.len(txn);
text.insert_with_attributes(txn, at, chunk, attrs);
i += 1;
}
continue;
}
let el = parent.insert(txn, index, XmlElementPrelim::empty(ty.as_str()));
if let Some(Value::Object(attrs)) = nodes[i].get("attrs") {
for (key, value) in attrs {
// y-prosemirror leaves null attributes out.
if !value.is_null() {
el.insert_attribute(txn, key.as_str(), json_any(value.clone())?);
}
}
}
if let Some(Value::Array(children)) = nodes[i].get("content") {
fill(txn, &el, children, depth + 1)?;
}
i += 1;
}
Ok(())
}
fn json_any(value: Value) -> Result<Any, String> {
serde_json::from_value(value).map_err(|e| e.to_string())
}
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 {
// get_string would wrap formatted runs in tags like <bold>; search wants plain text.
XmlOut::Text(t) => {
for d in t.diff(txn, YChange::identity) {
match d.insert {
Out::Any(Any::String(s)) => buf.push_str(&s),
other => buf.push_str(&other.to_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()),
}
}