Files
Docwell/Server/internal/ycrdt/ycrdt.go
T
tajniak81andClaude Opus 5.5 ba394b8fac Finish Phase 0: lint, codegen, contributor docs and the two remaining spikes
Repository basics:
- CONTRIBUTING.md and CODE_OF_CONDUCT.md (Contributor Covenant 2.1)
- SPDX AGPL-3.0-or-later headers on all hand-written sources, checked in CI
- golangci-lint (shared .golangci.yml), ESLint and Prettier, all run in CI

API codegen from api/openapi.yaml (npm run generate, drift fails CI):
- Go types via oapi-codegen in Server/internal/api
- a contract test that the router and the spec list the same routes
- Dart models via Phone-App/tool/generate_api.dart; the app uses them

Spike: shared Tiptap editor in a Flutter WebView (ADR-4)
- @docwell/editor-bridge builds the editor into one HTML page with a
  versioned JSON protocol; Phone-App hosts it with webview_flutter and a
  native toolbar. Integration test passes on an Android API 35 emulator.
- flutter_inappwebview dropped: its Android plugin fails on AGP 9.

Spike: Wails v3 desktop (ADR-11)
- system tray, docwell:// deep links (page and space only) with
  single-instance hand-off, and the built-in updater with a required
  ed25519 signing key. Verified on Windows.
- regenerated build assets register the scheme and drop template
  placeholders.

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

198 lines
6.4 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
// Package ycrdt runs yrs (the Rust Yjs port) compiled to WebAssembly under
// wazero, so the server can compact and read Yjs documents without cgo (ADR-3).
//
// 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 use a Pool.
//
// The module is built from Server/ycrdt-wasm (go generate ./internal/ycrdt).
package ycrdt
//go:generate sh ../../ycrdt-wasm/build.sh
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; cacheDir (optional) keeps the compiled code across restarts.
func New(ctx context.Context, cacheDir string) (*Runtime, error) {
cfg := wazero.NewRuntimeConfig()
if cacheDir != "" {
if cache, err := wazero.NewCompilationCacheWithDir(cacheDir); err == nil {
cfg = cfg.WithCompilationCache(cache)
}
}
rt := wazero.NewRuntimeWithConfig(ctx, cfg)
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
replace 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"),
replace: mod.ExportedFunction("dw_replace"),
}, 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
}
// Replace returns an update that replaces the document held by updates with
// ProseMirror JSON doc. Applied by every peer, it converges like any other edit.
func (i *Instance) Replace(ctx context.Context, updates [][]byte, doc []byte) ([]byte, error) {
return i.call(ctx, i.replace, Frame(updates), doc)
}
// 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 func() { _, _ = 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
}