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>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-10-31 11:52:55 +01:00
1 parent abf55a426b
commit 5e1dcf4291
45 files changed
+3480 -213

No files matched your search

+4 -3
View File
@@ -35,9 +35,10 @@ func CurrentUser(ctx context.Context) (auth.User, bool) {
}
type api struct {
auth AuthService
dir DirectoryService
log *slog.Logger
auth AuthService
dir DirectoryService
collab CollabHub
log *slog.Logger
}
func (a *api) requireUser(next http.HandlerFunc) http.HandlerFunc {
+138
View File
@@ -0,0 +1,138 @@
package httpapi
import (
"context"
"errors"
"net/http"
"net/url"
"time"
"github.com/coder/websocket"
"docwell/server/internal/collab"
)
// CollabHub is the part of collab.Hub the WebSocket endpoint uses.
type CollabHub interface {
Join(ctx context.Context, page, user string, canWrite bool, p collab.Peer) (*collab.Session, error)
}
// Close codes the editor reacts to (4000–4999 are free for applications).
const (
closeUnauthorized = 4401
closeNotFound = 4404
)
// collabRoute serves /collab?page=<id>: the y-websocket protocol for one page.
// Browsers cannot set headers on a WebSocket, and tokens in URLs end up in
// logs, so the first message must be a text frame holding the session token.
func (a *api) collabRoute(mux *http.ServeMux, origins []string) {
patterns := make([]string, 0, len(origins))
for _, o := range origins {
if u, err := url.Parse(o); err == nil && u.Host != "" {
patterns = append(patterns, u.Host)
}
}
mux.HandleFunc("GET /collab", func(w http.ResponseWriter, r *http.Request) {
if a.collab == nil {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "not_found"})
return
}
conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{OriginPatterns: patterns})
if err != nil {
return
}
defer conn.CloseNow()
conn.SetReadLimit(16 << 20)
a.serveCollab(r.Context(), conn, r.URL.Query().Get("page"))
})
}
func (a *api) serveCollab(ctx context.Context, conn *websocket.Conn, page string) {
authCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
typ, token, err := conn.Read(authCtx)
cancel()
if err != nil || typ != websocket.MessageText {
conn.Close(closeUnauthorized, "send the session token first")
return
}
user, err := a.auth.Verify(ctx, string(token))
if err != nil {
conn.Close(closeUnauthorized, "unauthorized")
return
}
canWrite, err := a.dir.CollabAccess(ctx, user.Caller(), page)
if err != nil {
conn.Close(closeNotFound, "page not found")
return
}
ctx, cancel = context.WithCancel(ctx)
defer cancel()
p := &wsPeer{out: make(chan []byte, 1024), cancel: cancel}
go p.write(ctx, conn)
session, err := a.collab.Join(ctx, page, user.ID, canWrite, p)
if err != nil {
a.log.Error("collab: join", "page", page, "err", err)
conn.Close(websocket.StatusInternalError, "could not open the page")
return
}
defer session.Leave()
for {
typ, msg, err := conn.Read(ctx)
if err != nil {
return
}
if typ != websocket.MessageBinary {
continue
}
if err := session.Receive(ctx, msg); err != nil {
conn.Close(websocket.StatusUnsupportedData, "malformed message")
return
}
}
}
// wsPeer queues outgoing messages; a peer that falls 1024 messages behind is
// disconnected and catches up through a fresh sync when it reconnects.
type wsPeer struct {
out chan []byte
cancel context.CancelFunc
}
func (p *wsPeer) Send(msg []byte) bool {
select {
case p.out <- msg:
return true
default:
p.cancel()
return false
}
}
func (p *wsPeer) write(ctx context.Context, conn *websocket.Conn) {
ping := time.NewTicker(30 * time.Second)
defer ping.Stop()
for {
select {
case msg := <-p.out:
wctx, cancel := context.WithTimeout(ctx, 10*time.Second)
err := conn.Write(wctx, websocket.MessageBinary, msg)
cancel()
if err != nil {
p.cancel()
return
}
case <-ping.C:
pctx, cancel := context.WithTimeout(ctx, 10*time.Second)
err := conn.Ping(pctx)
cancel()
if err != nil && !errors.Is(err, context.Canceled) {
p.cancel()
return
}
case <-ctx.Done():
return
}
}
}
+10 -3
View File
@@ -21,13 +21,17 @@ type Deps struct {
DB Pinger
Auth AuthService
Directory DirectoryService
Admin http.Handler
Log *slog.Logger
// Collab serves /collab; nil disables live editing.
Collab CollabHub
Admin http.Handler
Log *slog.Logger
}
func NewRouter(d Deps) http.Handler {
mux := http.NewServeMux()
(&api{auth: d.Auth, dir: d.Directory, log: d.Log}).routes(mux)
a := &api{auth: d.Auth, dir: d.Directory, collab: d.Collab, log: d.Log}
a.routes(mux)
a.collabRoute(mux, d.CORSOrigins)
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
@@ -88,6 +92,9 @@ type statusRecorder struct {
status int
}
// Unwrap lets the WebSocket upgrade reach the connection's Hijacker.
func (s *statusRecorder) Unwrap() http.ResponseWriter { return s.ResponseWriter }
func (s *statusRecorder) WriteHeader(code int) {
s.status = code
s.ResponseWriter.WriteHeader(code)
+17
View File
@@ -5,6 +5,7 @@ import (
"net/http"
"docwell/server/internal/access"
"docwell/server/internal/collab"
"docwell/server/internal/directory"
)
@@ -25,6 +26,10 @@ type SpaceService interface {
UpdatePage(ctx context.Context, c access.Caller, id string, in directory.UpdatePageInput) (directory.Page, error)
GetPageContent(ctx context.Context, c access.Caller, id string) (directory.PageContent, error)
SavePageContent(ctx context.Context, c access.Caller, id string, in directory.SavePageContentInput) (directory.PageContent, error)
CollabAccess(ctx context.Context, c access.Caller, id string) (canWrite bool, err error)
ListVersions(ctx context.Context, c access.Caller, id string) ([]collab.Version, error)
GetVersion(ctx context.Context, c access.Caller, id, versionID string) (directory.PageContent, error)
RestoreVersion(ctx context.Context, c access.Caller, id, versionID string) (directory.PageContent, error)
MovePage(ctx context.Context, c access.Caller, id string, in directory.MovePageInput) (directory.Page, error)
TrashPage(ctx context.Context, c access.Caller, id string) error
RestorePage(ctx context.Context, c access.Caller, id string) (directory.Page, error)
@@ -118,6 +123,18 @@ func (a *api) spaceRoutes(mux *http.ServeMux) {
c, err := a.dir.SavePageContent(r.Context(), caller(r), r.PathValue("id"), in)
a.respond(w, c, err)
}))
mux.HandleFunc("GET /api/v1/pages/{id}/versions", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
v, err := a.dir.ListVersions(r.Context(), caller(r), r.PathValue("id"))
a.respond(w, v, err)
}))
mux.HandleFunc("GET /api/v1/pages/{id}/versions/{versionId}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
c, err := a.dir.GetVersion(r.Context(), caller(r), r.PathValue("id"), r.PathValue("versionId"))
a.respond(w, c, err)
}))
mux.HandleFunc("POST /api/v1/pages/{id}/versions/{versionId}/restore", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
c, err := a.dir.RestoreVersion(r.Context(), caller(r), r.PathValue("id"), r.PathValue("versionId"))
a.respond(w, c, err)
}))
mux.HandleFunc("POST /api/v1/pages/{id}/move", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
var in directory.MovePageInput
if !a.decode(w, r, &in) {