// SPDX-License-Identifier: AGPL-3.0-or-later // Package collab relays Yjs updates between the editors of a page and // persists them (PLAN.md ยง6, ADR-3). // // Each open page is a room kept in memory. Updates are relayed to the other // peers at once, appended to page_yupdates every second, and compacted into // page_ydoc (with content_json and content_text derived from it) after a pause // in editing or when the last peer leaves. A page version is recorded at most // every VersionEvery while people edit, and when the last peer leaves. package collab import ( "context" "encoding/json" "errors" "fmt" "log/slog" "sync" "time" "docwell/server/internal/ycrdt" ) var ErrNotFound = errors.New("not found") type Options struct { Store Store Docs *ycrdt.Pool Log *slog.Logger // FlushEvery is how often new updates are written to the database (1 s). FlushEvery time.Duration // IdleCompact is the pause in editing after which a room compacts (30 s). IdleCompact time.Duration // VersionEvery is the minimum gap between history versions while editing (10 min). VersionEvery time.Duration } type Hub struct { o Options onSaved func(page, editor string, doc []byte) mu sync.Mutex rooms map[string]*room done chan struct{} wg sync.WaitGroup } // OnSaved registers fn to run (in its own goroutine) after a page's content // was saved, with the last editor and the document as Tiptap JSON. Set it // before the hub serves anyone. func (h *Hub) OnSaved(fn func(page, editor string, doc []byte)) { h.onSaved = fn } func NewHub(o Options) *Hub { if o.FlushEvery == 0 { o.FlushEvery = time.Second } if o.IdleCompact == 0 { o.IdleCompact = 30 * time.Second } if o.VersionEvery == 0 { o.VersionEvery = 10 * time.Minute } if o.Log == nil { o.Log = slog.Default() } return &Hub{o: o, rooms: map[string]*room{}, done: make(chan struct{})} } // Close persists every open room. Peers are expected to be gone (the HTTP // server shuts down first). func (h *Hub) Close(ctx context.Context) error { close(h.done) finished := make(chan struct{}) go func() { h.wg.Wait(); close(finished) }() select { case <-finished: return nil case <-ctx.Done(): return ctx.Err() } } // Stats counts the open pages and their connected editors. type Stats struct { Rooms int `json:"rooms"` Peers int `json:"peers"` } // Stats reports what is open right now (for the admin dashboard). func (h *Hub) Stats() Stats { h.mu.Lock() rooms := make([]*room, 0, len(h.rooms)) for _, r := range h.rooms { rooms = append(rooms, r) } h.mu.Unlock() st := Stats{Rooms: len(rooms)} for _, r := range rooms { r.mu.Lock() st.Peers += len(r.sessions) r.mu.Unlock() } return st } // Peer is the sending side of one connection. Send must not block; it returns // false when the peer cannot keep up and is being disconnected. type Peer interface { Send(msg []byte) bool // Close disconnects the peer with a WebSocket close code. Close(code int, reason string) } // Close codes sent to peers (the editor reacts to them). const ( // CloseAccessChanged asks the peer to reload the page and reconnect: its // rights changed, or the page was trashed or restored. CloseAccessChanged = 4409 // CloseGone means the page no longer exists. CloseGone = 4404 ) type room struct { h *Hub page string ready chan struct{} err error mu sync.Mutex closed bool sessions map[*Session]struct{} snapshot []byte // compacted document pending [][]byte // updates not yet compacted into snapshot unflushed [][]byte // updates not yet written to page_yupdates flushed []string // page_yupdates records not yet covered by a saved snapshot dirty bool // changes since the last saved snapshot unversion bool // changes since the last version editor string // last user who changed the document lastEdit time.Time lastVer time.Time } // acquire returns the loaded room for page, loading it if needed. func (h *Hub) acquire(ctx context.Context, page string) (*room, error) { h.mu.Lock() select { case <-h.done: h.mu.Unlock() return nil, errors.New("collab: shutting down") default: } r := h.rooms[page] if r == nil { r = &room{h: h, page: page, ready: make(chan struct{}), sessions: map[*Session]struct{}{}} h.rooms[page] = r h.wg.Add(1) go r.run() //nolint:gosec // a room outlives the request that opened it } h.mu.Unlock() select { case <-r.ready: case <-ctx.Done(): return nil, ctx.Err() } if r.err != nil { return nil, r.err } return r, nil } // withRoom runs fn on the open room for page, retrying if it closed meanwhile. func (h *Hub) withRoom(ctx context.Context, page string, fn func(r *room) error) error { for { r, err := h.acquire(ctx, page) if err != nil { return err } r.mu.Lock() if r.closed { r.mu.Unlock() continue } err = fn(r) r.mu.Unlock() return err } } func (r *room) load(ctx context.Context) error { o := r.h.o stored, err := o.Store.Load(ctx, r.page) if err != nil { return err } r.lastVer = stored.LastVersion r.unversion = stored.Unversioned r.flushed = stored.UpdateIDs var parts [][]byte if stored.Snapshot != nil { parts = append(parts, stored.Snapshot) } parts = append(parts, stored.Updates...) if len(parts) == 0 && string(stored.ContentJSON) != "null" && len(stored.ContentJSON) > 0 { // A page saved before collaboration: seed the document from its JSON. // The seed is persisted before the room closes, so every peer shares it. seed, err := o.Docs.Replace(ctx, nil, stored.ContentJSON) if err != nil { return err } parts = [][]byte{seed} r.unflushed = [][]byte{seed} r.dirty, r.unversion = true, true } if r.snapshot, err = o.Docs.Compact(ctx, parts); err != nil { return err } r.dirty = r.dirty || len(stored.Updates) > 0 return nil } func (r *room) run() { defer r.h.wg.Done() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) r.err = r.load(ctx) cancel() if r.err != nil { r.h.o.Log.Error("collab: load page", "page", r.page, "err", r.err) r.h.mu.Lock() delete(r.h.rooms, r.page) r.h.mu.Unlock() close(r.ready) return } close(r.ready) t := time.NewTicker(r.h.o.FlushEvery) defer t.Stop() for { select { case <-t.C: if r.tick(false) { return } case <-r.h.done: r.tick(true) return } } } // tick flushes, compacts when due and closes an empty, saved room. It reports // whether the room closed. func (r *room) tick(final bool) bool { o := r.h.o ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() r.mu.Lock() if r.closed { // dropped by Drop r.mu.Unlock() return true } batch := r.unflushed r.unflushed = nil r.mu.Unlock() if len(batch) > 0 { merged, err := o.Docs.Merge(ctx, batch) var id string if err == nil { id, err = o.Store.AppendUpdate(ctx, r.page, merged) } if err != nil && r.gone(ctx) { return true } r.mu.Lock() if err != nil { o.Log.Error("collab: flush updates", "page", r.page, "err", err) r.unflushed = append(batch, r.unflushed...) } else { r.flushed = append(r.flushed, id) } r.mu.Unlock() } r.mu.Lock() empty := len(r.sessions) == 0 failed := false if r.dirty && (final || empty || time.Since(r.lastEdit) >= o.IdleCompact || len(r.pending) >= 200) { failed = !r.persistLocked(ctx, final || empty) } r.mu.Unlock() if failed && r.gone(ctx) { return true } if final { return true } r.h.mu.Lock() defer r.h.mu.Unlock() r.mu.Lock() defer r.mu.Unlock() if len(r.sessions) == 0 && !r.dirty && len(r.unflushed) == 0 { r.closed = true if r.h.rooms[r.page] == r { delete(r.h.rooms, r.page) } return true } return false } // gone checks, after a failed write, whether the page was deleted (directly // or with its space or workspace). If so the room is dropped and its peers // disconnected, instead of retrying forever. func (r *room) gone(ctx context.Context) bool { if _, err := r.h.o.Store.Content(ctx, r.page); !errors.Is(err, ErrNotFound) { return false } r.h.Drop(r.page) return true } // persistLocked saves the compacted snapshot, its derived content and, when // due, a version. It releases r.mu while talking to the database, and // reports whether the save worked. func (r *room) persistLocked(ctx context.Context, leaving bool) bool { o := r.h.o state, err := r.compactLocked(ctx) if err != nil { o.Log.Error("collab: compact", "page", r.page, "err", err) return false } snap := Snapshot{State: state, LastEditor: r.editor, Covers: r.flushed} // Unflushed updates are part of state, so they need no record of their own. r.flushed, r.unflushed, r.dirty = nil, nil, false version := r.unversion && (leaving || time.Since(r.lastVer) >= o.VersionEvery) if version { r.unversion, r.lastVer = false, time.Now() } r.mu.Unlock() read, err := o.Docs.Read(ctx, state) if err == nil { snap.JSON, snap.Text = read.JSON, read.Text err = o.Store.SaveSnapshot(ctx, r.page, snap) } if err == nil && r.h.onSaved != nil { go r.h.onSaved(r.page, snap.LastEditor, snap.JSON) } if err == nil && version { if verr := o.Store.AddVersion(ctx, r.page, snap); verr != nil { o.Log.Error("collab: add version", "page", r.page, "err", verr) } } r.mu.Lock() if err != nil { o.Log.Error("collab: save snapshot", "page", r.page, "err", err) // Queue the whole state as an update instead: applying it twice is harmless. r.dirty = true r.unflushed = append([][]byte{state}, r.unflushed...) r.flushed = append(snap.Covers, r.flushed...) r.unversion = r.unversion || version return false } return true } // compactLocked folds pending updates into the snapshot (in memory only). func (r *room) compactLocked(ctx context.Context) ([]byte, error) { if len(r.pending) == 0 { return r.snapshot, nil } snap, err := r.h.o.Docs.Compact(ctx, append([][]byte{r.snapshot}, r.pending...)) if err != nil { return nil, err } r.snapshot, r.pending = snap, nil return snap, nil } // applyLocked records an update and relays it to every session except from. func (r *room) applyLocked(from *Session, update []byte, user string) { r.pending = append(r.pending, update) r.unflushed = append(r.unflushed, update) r.dirty, r.unversion = true, true r.lastEdit = time.Now() if user != "" { r.editor = user } msg := syncMessage(syncUpdate, update) for s := range r.sessions { if s != from { s.peer.Send(msg) } } } func (r *room) broadcastLocked(from *Session, msg []byte) { for s := range r.sessions { if s != from { s.peer.Send(msg) } } } // Session is one peer in a room. type Session struct { room *room peer Peer user string canWrite bool aware map[uint64]awarenessState } // Join adds a peer to the page's room and starts the sync: the server sends // its state vector (sync step 1) and the other peers' awareness states. func (h *Hub) Join(ctx context.Context, page, user string, canWrite bool, p Peer) (*Session, error) { var s *Session err := h.withRoom(ctx, page, func(r *room) error { snap, err := r.compactLocked(ctx) if err != nil { return err } sv, err := h.o.Docs.StateVector(ctx, snap) if err != nil { return err } s = &Session{room: r, peer: p, user: user, canWrite: canWrite, aware: map[uint64]awarenessState{}} r.sessions[s] = struct{}{} p.Send(syncMessage(syncStep1, sv)) if states := r.awarenessLocked(s); len(states) > 0 { p.Send(awarenessMessage(encodeAwareness(states))) } return nil }) return s, err } func (r *room) awarenessLocked(except *Session) map[uint64]awarenessState { all := map[uint64]awarenessState{} for s := range r.sessions { if s != except { for id, st := range s.aware { all[id] = st } } } return all } // Receive handles one binary message from the peer. func (s *Session) Receive(ctx context.Context, msg []byte) error { r := s.room d := decoder{msg} typ, err := d.uint() if err != nil { return err } switch typ { case msgSync: step, err := d.uint() if err != nil { return err } payload, err := d.bytes() if err != nil { return err } switch step { case syncStep1: r.mu.Lock() snap, err := r.compactLocked(ctx) r.mu.Unlock() if err != nil { return err } diff, err := r.h.o.Docs.Diff(ctx, snap, payload) if err != nil { return errMalformed } s.peer.Send(syncMessage(syncStep2, diff)) case syncStep2, syncUpdate: // Read-only peers' edits are dropped, as y-websocket does. if !s.canWrite || isEmptyUpdate(payload) { return nil } // Parsing the update rejects garbage before it can poison the log. if _, err := r.h.o.Docs.StateVector(ctx, payload); err != nil { return errMalformed } r.mu.Lock() r.applyLocked(s, payload, s.user) r.mu.Unlock() default: return errMalformed } case msgAwareness: update, err := d.bytes() if err != nil { return err } states, err := decodeAwareness(update) if err != nil { return err } r.mu.Lock() for id, st := range states { if st.state == "null" { delete(s.aware, id) } else { s.aware[id] = st } } r.broadcastLocked(s, awarenessMessage(update)) r.mu.Unlock() case msgQueryAwareness: r.mu.Lock() states := r.awarenessLocked(s) r.mu.Unlock() if len(states) > 0 { s.peer.Send(awarenessMessage(encodeAwareness(states))) } default: return errMalformed } return nil } // Leave removes the peer and tells the others its cursors are gone. Idempotent. func (s *Session) Leave() { r := s.room r.mu.Lock() defer r.mu.Unlock() if _, ok := r.sessions[s]; !ok { return } delete(r.sessions, s) if len(s.aware) > 0 { gone := make(map[uint64]awarenessState, len(s.aware)) for id, st := range s.aware { gone[id] = awarenessState{clock: st.clock + 1, state: "null"} } r.broadcastLocked(nil, awarenessMessage(encodeAwareness(gone))) } } // An update with no structs and no deletions: [0 structs][0 delete sets]. func isEmptyUpdate(u []byte) bool { return len(u) == 2 && u[0] == 0 && u[1] == 0 } // Replace replaces the page's document with ProseMirror JSON as an edit by // user, so connected editors see it like any other change. Changes made since // the last version are first kept as a version named label (a code the UI // translates, e.g. "before-restore"), so a restore or // import never loses them. func (h *Hub) Replace(ctx context.Context, page, user string, doc json.RawMessage, label string) error { return h.withRoom(ctx, page, func(r *room) error { if r.unversion { state, err := r.compactLocked(ctx) if err != nil { return err } read, err := h.o.Docs.Read(ctx, state) if err != nil { return err } snap := Snapshot{State: state, JSON: read.JSON, Text: read.Text, LastEditor: r.editor, Label: label} if err := h.o.Store.AddVersion(ctx, page, snap); err != nil { return err } r.unversion, r.lastVer = false, time.Now() } update, err := h.o.Docs.Replace(ctx, append([][]byte{r.snapshot}, r.pending...), doc) if err != nil { return err } r.applyLocked(nil, update, user) return nil }) } // Kick disconnects everyone on the page with CloseAccessChanged, so their // editors reconnect with fresh rights (after the page was trashed or restored). func (h *Hub) Kick(page string) { h.mu.Lock() r := h.rooms[page] h.mu.Unlock() if r == nil { return } r.mu.Lock() defer r.mu.Unlock() for s := range r.sessions { s.peer.Close(CloseAccessChanged, "access changed") } } // Drop discards the page's room without saving and disconnects its peers: // the page was deleted. func (h *Hub) Drop(page string) { h.mu.Lock() r := h.rooms[page] if r != nil { delete(h.rooms, page) } h.mu.Unlock() if r == nil { return } <-r.ready r.mu.Lock() defer r.mu.Unlock() r.closed = true for s := range r.sessions { s.peer.Close(CloseGone, "page deleted") } r.sessions = map[*Session]struct{}{} } // Content returns the page's current document as ProseMirror JSON: live from // an open room, otherwise as last saved. func (h *Hub) Content(ctx context.Context, page string) (json.RawMessage, error) { h.mu.Lock() r := h.rooms[page] h.mu.Unlock() if r != nil { select { case <-r.ready: case <-ctx.Done(): return nil, ctx.Err() } r.mu.Lock() if !r.closed && r.err == nil { snap, err := r.compactLocked(ctx) r.mu.Unlock() if err != nil { return nil, err } read, err := h.o.Docs.Read(ctx, snap) return read.JSON, err } r.mu.Unlock() } return h.o.Store.Content(ctx, page) } // State returns the page's whole document as one Yjs update (the encoding // Y.encodeStateAsUpdate writes): live from an open room, otherwise loaded. func (h *Hub) State(ctx context.Context, page string) ([]byte, error) { var state []byte err := h.withRoom(ctx, page, func(r *room) error { snap, err := r.compactLocked(ctx) state = append([]byte(nil), snap...) return err }) return state, err } // Apply merges a Yjs update into the page as an edit by user (a restored // snapshot's state). An update the document engine cannot read is refused // before it reaches the room. func (h *Hub) Apply(ctx context.Context, page, user string, update []byte) error { return h.withRoom(ctx, page, func(r *room) error { if _, err := h.o.Docs.Compact(ctx, append(append([][]byte{r.snapshot}, r.pending...), update)); err != nil { return fmt.Errorf("collab: unreadable update: %w", err) } r.applyLocked(nil, update, user) return nil }) } func (h *Hub) Versions(ctx context.Context, page string) ([]Version, error) { return h.o.Store.Versions(ctx, page) } func (h *Hub) VersionContent(ctx context.Context, page, id string) (json.RawMessage, error) { return h.o.Store.VersionContent(ctx, page, id) }