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>
283 lines
7.6 KiB
Go
283 lines
7.6 KiB
Go
package collab
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"docwell/server/internal/ycrdt"
|
|
)
|
|
|
|
type memStore struct {
|
|
mu sync.Mutex
|
|
snapshot map[string][]byte
|
|
updates map[string][][]byte
|
|
content map[string]json.RawMessage
|
|
versions map[string][]Snapshot
|
|
}
|
|
|
|
func newMemStore() *memStore {
|
|
return &memStore{snapshot: map[string][]byte{}, updates: map[string][][]byte{}, content: map[string]json.RawMessage{}, versions: map[string][]Snapshot{}}
|
|
}
|
|
|
|
func (m *memStore) Load(_ context.Context, page string) (Stored, error) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
s := Stored{Snapshot: m.snapshot[page], Updates: m.updates[page]}
|
|
if s.Snapshot == nil && len(s.Updates) == 0 {
|
|
s.ContentJSON = m.content[page]
|
|
}
|
|
return s, nil
|
|
}
|
|
|
|
func (m *memStore) AppendUpdate(_ context.Context, page string, u []byte) (string, error) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
m.updates[page] = append(m.updates[page], u)
|
|
return "u", nil
|
|
}
|
|
|
|
func (m *memStore) SaveSnapshot(_ context.Context, page string, s Snapshot) error {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
m.snapshot[page], m.updates[page], m.content[page] = s.State, nil, s.JSON
|
|
return nil
|
|
}
|
|
|
|
func (m *memStore) AddVersion(_ context.Context, page string, s Snapshot) error {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
m.versions[page] = append(m.versions[page], s)
|
|
return nil
|
|
}
|
|
|
|
func (m *memStore) Content(_ context.Context, page string) (json.RawMessage, error) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
return nullIfEmpty(m.content[page]), nil
|
|
}
|
|
|
|
func (m *memStore) Versions(context.Context, string) ([]Version, error) { return nil, nil }
|
|
|
|
func (m *memStore) VersionContent(context.Context, string, string) (json.RawMessage, error) {
|
|
return nil, ErrNotFound
|
|
}
|
|
|
|
// fakePeer collects what the hub sends it.
|
|
type fakePeer struct {
|
|
mu sync.Mutex
|
|
msgs [][]byte
|
|
}
|
|
|
|
func (p *fakePeer) Send(msg []byte) bool {
|
|
p.mu.Lock()
|
|
defer p.mu.Unlock()
|
|
p.msgs = append(p.msgs, msg)
|
|
return true
|
|
}
|
|
|
|
// take returns and clears the messages of one type (and sync step, if typ is msgSync).
|
|
func (p *fakePeer) take(typ, step uint64) [][]byte {
|
|
p.mu.Lock()
|
|
defer p.mu.Unlock()
|
|
var out, rest [][]byte
|
|
for _, m := range p.msgs {
|
|
d := decoder{m}
|
|
t, _ := d.uint()
|
|
match := t == typ
|
|
if match && typ == msgSync {
|
|
s, _ := d.uint()
|
|
match = s == step
|
|
}
|
|
if match {
|
|
payload, _ := d.bytes()
|
|
out = append(out, payload)
|
|
} else {
|
|
rest = append(rest, m)
|
|
}
|
|
}
|
|
p.msgs = rest
|
|
return out
|
|
}
|
|
|
|
func newHub(t *testing.T, store Store) (*Hub, *ycrdt.Pool) {
|
|
t.Helper()
|
|
ctx := context.Background()
|
|
rt, err := ycrdt.New(ctx, "")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { rt.Close(ctx) })
|
|
pool := ycrdt.NewPool(rt, 2)
|
|
h := NewHub(Options{Store: store, Docs: pool, FlushEvery: 10 * time.Millisecond, IdleCompact: time.Hour})
|
|
return h, pool
|
|
}
|
|
|
|
func docJSON(text string) []byte {
|
|
return []byte(`{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"` + text + `"}]}]}`)
|
|
}
|
|
|
|
func textOf(t *testing.T, pool *ycrdt.Pool, updates ...[]byte) string {
|
|
t.Helper()
|
|
snap, err := pool.Compact(context.Background(), updates)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
r, err := pool.Read(context.Background(), snap)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return strings.TrimSpace(r.Text)
|
|
}
|
|
|
|
func waitFor(t *testing.T, what string, cond func() bool) {
|
|
t.Helper()
|
|
for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); time.Sleep(5 * time.Millisecond) {
|
|
if cond() {
|
|
return
|
|
}
|
|
}
|
|
t.Fatalf("timed out waiting for %s", what)
|
|
}
|
|
|
|
func TestRelayAndPersist(t *testing.T) {
|
|
ctx := context.Background()
|
|
store := newMemStore()
|
|
h, pool := newHub(t, store)
|
|
|
|
alice, viewer := &fakePeer{}, &fakePeer{}
|
|
sa, err := h.Join(ctx, "p1", "alice", true, alice)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(alice.take(msgSync, syncStep1)) != 1 {
|
|
t.Fatal("join should send sync step 1")
|
|
}
|
|
sv, err := h.Join(ctx, "p1", "", false, viewer)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
// Alice types; the viewer gets the update relayed, Alice does not get it back.
|
|
edit, err := pool.Replace(ctx, nil, docJSON("hello"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := sa.Receive(ctx, syncMessage(syncUpdate, edit)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := viewer.take(msgSync, syncUpdate); len(got) != 1 || textOf(t, pool, got[0]) != "hello" {
|
|
t.Fatalf("viewer got %d updates", len(got))
|
|
}
|
|
if len(alice.take(msgSync, syncUpdate)) != 0 {
|
|
t.Fatal("update echoed to its sender")
|
|
}
|
|
|
|
// The viewer's edits are dropped.
|
|
vandal, _ := pool.Replace(ctx, [][]byte{edit}, docJSON("defaced"))
|
|
if err := sv.Receive(ctx, syncMessage(syncUpdate, vandal)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(alice.take(msgSync, syncUpdate)) != 0 {
|
|
t.Fatal("read-only edit relayed")
|
|
}
|
|
|
|
// A late joiner asks with an empty state vector and gets the whole document.
|
|
bob := &fakePeer{}
|
|
sb, err := h.Join(ctx, "p1", "bob", true, bob)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := sb.Receive(ctx, syncMessage(syncStep1, []byte{0})); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := bob.take(msgSync, syncStep2); len(got) != 1 || textOf(t, pool, got[0]) != "hello" {
|
|
t.Fatalf("late joiner step 2 = %d messages", len(got))
|
|
}
|
|
|
|
// Awareness is relayed, and cleared for the others when a peer leaves.
|
|
aw := encodeAwareness(map[uint64]awarenessState{42: {clock: 3, state: `{"user":{"name":"Bob"}}`}})
|
|
if err := sb.Receive(ctx, awarenessMessage(aw)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(alice.take(msgAwareness, 0)) != 1 {
|
|
t.Fatal("awareness not relayed")
|
|
}
|
|
sb.Leave()
|
|
got := alice.take(msgAwareness, 0)
|
|
if len(got) != 1 {
|
|
t.Fatal("no awareness removal")
|
|
}
|
|
if states, _ := decodeAwareness(got[0]); states[42].state != "null" || states[42].clock != 4 {
|
|
t.Fatalf("removal = %+v", states)
|
|
}
|
|
|
|
// Malformed input is rejected without breaking the room.
|
|
if err := sa.Receive(ctx, syncMessage(syncUpdate, []byte{1, 2, 3, 4, 5})); err == nil {
|
|
t.Fatal("garbage update accepted")
|
|
}
|
|
|
|
// When everyone leaves, the room saves the snapshot, content and a version.
|
|
sa.Leave()
|
|
sv.Leave()
|
|
waitFor(t, "room to close", func() bool {
|
|
h.mu.Lock()
|
|
defer h.mu.Unlock()
|
|
return h.rooms["p1"] == nil
|
|
})
|
|
content, _ := store.Content(ctx, "p1")
|
|
if !strings.Contains(string(content), `"hello"`) {
|
|
t.Fatalf("saved content = %s", content)
|
|
}
|
|
if v := store.versions["p1"]; len(v) != 1 || v[0].LastEditor != "alice" {
|
|
t.Fatalf("versions = %+v", v)
|
|
}
|
|
if len(store.updates["p1"]) != 0 {
|
|
t.Fatal("flushed updates not pruned after the snapshot")
|
|
}
|
|
}
|
|
|
|
func TestSeedFromJSONAndReplace(t *testing.T) {
|
|
ctx := context.Background()
|
|
store := newMemStore()
|
|
store.content["p2"] = docJSON("from before collab")
|
|
h, pool := newHub(t, store)
|
|
|
|
c, err := h.Content(ctx, "p2")
|
|
if err != nil || !strings.Contains(string(c), "from before collab") {
|
|
t.Fatalf("content before open = %s, %v", c, err)
|
|
}
|
|
peer := &fakePeer{}
|
|
s, err := h.Join(ctx, "p2", "alice", true, peer)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := s.Receive(ctx, syncMessage(syncStep1, []byte{0})); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := peer.take(msgSync, syncStep2); len(got) != 1 || textOf(t, pool, got[0]) != "from before collab" {
|
|
t.Fatal("seed not served")
|
|
}
|
|
|
|
// A REST replace reaches connected peers as an ordinary update.
|
|
if err := h.Replace(ctx, "p2", "bob", docJSON("restored")); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := peer.take(msgSync, syncUpdate); len(got) != 1 {
|
|
t.Fatal("replace not relayed")
|
|
}
|
|
if c, _ := h.Content(ctx, "p2"); !strings.Contains(string(c), "restored") {
|
|
t.Fatalf("live content = %s", c)
|
|
}
|
|
s.Leave()
|
|
if err := h.Close(ctx); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if c, _ := store.Content(ctx, "p2"); !strings.Contains(string(c), "restored") {
|
|
t.Fatalf("saved content = %s", c)
|
|
}
|
|
}
|