Phase F of the AFFiNE plan (ADR-16): - Calendars: people subscribe to iCal feeds (webcal, Google's secret address, Outlook) or CalDAV accounts in account settings; their events show at the top of journal pages in the reader's time zone. Repeats, moved and cancelled occurrences, IANA and Windows zones are handled. Events are read on demand and kept in memory for 15 minutes; passwords are sealed with DOCWELL_SECRET_KEY; sources follow the webhook address rules. New calendar_accounts collection. - Importers: zips of Markdown (Obsidian vaults, Bear TextBundles and .bear2bk, Readwise's Markdown, Docwell's own space export) keep folders as pages, resolve [[wikilinks]] and embeds by name, and turn front matter and #tags into properties and tags. OneNote .mht exports, Readwise CSV, and any other CSV as a database page. - Exports: PNG of a page drawn in the browser, print styles that print only the page in the light theme, and workspace snapshots (records, Yjs states, JSON and files in one zip) that restore as a new workspace. Old ids are swapped byte for byte inside the Yjs updates, so links point at the restored pages and comments stay anchored. - Web-Clipper/: a Manifest V3 extension for Chrome, Edge and Firefox that saves the article or the selection as Markdown through the import API with a personal API token. - OpenAPI, generated clients, translations and user docs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
396 lines
11 KiB
Go
396 lines
11 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
package collab
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"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
|
|
deleted map[string]bool
|
|
}
|
|
|
|
func newMemStore() *memStore {
|
|
return &memStore{
|
|
snapshot: map[string][]byte{}, updates: map[string][][]byte{}, content: map[string]json.RawMessage{},
|
|
versions: map[string][]Snapshot{}, deleted: map[string]bool{},
|
|
}
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
var errBadRelation = errors.New("page relation is invalid")
|
|
|
|
func (m *memStore) AppendUpdate(_ context.Context, page string, u []byte) (string, error) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
if m.deleted[page] {
|
|
return "", errBadRelation
|
|
}
|
|
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()
|
|
if m.deleted[page] {
|
|
return nil, ErrNotFound
|
|
}
|
|
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
|
|
closed int // close code, 0 while open
|
|
}
|
|
|
|
func (p *fakePeer) Close(code int, _ string) {
|
|
p.mu.Lock()
|
|
defer p.mu.Unlock()
|
|
p.closed = code
|
|
}
|
|
|
|
func (p *fakePeer) closeCode() int {
|
|
p.mu.Lock()
|
|
defer p.mu.Unlock()
|
|
return p.closed
|
|
}
|
|
|
|
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"), "before-restore"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := peer.take(msgSync, syncUpdate); len(got) != 1 {
|
|
t.Fatal("replace not relayed")
|
|
}
|
|
// The seeded text had no version yet, so the replace kept one first.
|
|
if v := store.versions["p2"]; len(v) != 1 || v[0].Label != "before-restore" || !strings.Contains(string(v[0].JSON), "from before collab") {
|
|
t.Fatalf("versions before replace = %+v", v)
|
|
}
|
|
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)
|
|
}
|
|
}
|
|
|
|
func TestKickAndDrop(t *testing.T) {
|
|
ctx := context.Background()
|
|
store := newMemStore()
|
|
h, _ := newHub(t, store)
|
|
|
|
peer := &fakePeer{}
|
|
if _, err := h.Join(ctx, "p3", "alice", true, peer); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
h.Kick("p3")
|
|
if peer.closeCode() != CloseAccessChanged {
|
|
t.Fatalf("kick close code = %d", peer.closeCode())
|
|
}
|
|
h.Drop("p3")
|
|
if peer.closeCode() != CloseGone {
|
|
t.Fatalf("drop close code = %d", peer.closeCode())
|
|
}
|
|
h.mu.Lock()
|
|
defer h.mu.Unlock()
|
|
if h.rooms["p3"] != nil {
|
|
t.Fatal("dropped room still open")
|
|
}
|
|
}
|
|
|
|
// A page deleted with its space (no Drop call) is noticed on the next failed
|
|
// write, instead of retrying forever.
|
|
func TestDeletedPageClosesRoom(t *testing.T) {
|
|
ctx := context.Background()
|
|
store := newMemStore()
|
|
h, pool := newHub(t, store)
|
|
|
|
peer := &fakePeer{}
|
|
s, err := h.Join(ctx, "p4", "alice", true, peer)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
store.mu.Lock()
|
|
store.deleted["p4"] = true
|
|
store.mu.Unlock()
|
|
edit, _ := pool.Replace(ctx, nil, docJSON("lost"))
|
|
if err := s.Receive(ctx, syncMessage(syncUpdate, edit)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
waitFor(t, "room of a deleted page to close", func() bool {
|
|
h.mu.Lock()
|
|
defer h.mu.Unlock()
|
|
return h.rooms["p4"] == nil && peer.closeCode() == CloseGone
|
|
})
|
|
}
|
|
|
|
func TestStateAndApply(t *testing.T) {
|
|
ctx := context.Background()
|
|
store := newMemStore()
|
|
h, pool := newHub(t, store)
|
|
if err := h.Replace(ctx, "src", "alice", docJSON("copied over"), "import"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
state, err := h.State(ctx, "src")
|
|
if err != nil || len(state) == 0 {
|
|
t.Fatalf("state = %d bytes, %v", len(state), err)
|
|
}
|
|
if textOf(t, pool, state) != "copied over" {
|
|
t.Fatal("state does not hold the document")
|
|
}
|
|
if err := h.Apply(ctx, "dst", "bob", state); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if c, _ := h.Content(ctx, "dst"); !strings.Contains(string(c), "copied over") {
|
|
t.Fatalf("applied content = %s", c)
|
|
}
|
|
if err := h.Apply(ctx, "dst", "bob", []byte{1, 2, 3, 4, 5}); err == nil {
|
|
t.Fatal("an unreadable update was applied")
|
|
}
|
|
if c, _ := h.Content(ctx, "dst"); !strings.Contains(string(c), "copied over") {
|
|
t.Fatalf("content after a refused update = %s", c)
|
|
}
|
|
if err := h.Close(ctx); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|