Files
Docwell/Server/internal/collab/store.go
T
tajniak81andClaude Opus 5.5 5e1dcf4291 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>
2026-10-31 11:52:55 +01:00

231 lines
7.2 KiB
Go

package collab
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"strings"
"time"
"docwell/server/internal/store/pocketbase"
)
// Stored is what a room loads from the database.
type Stored struct {
// Snapshot is the compacted document (nil when there is none yet).
Snapshot []byte
// Updates are flushed updates newer than the snapshot, oldest first.
Updates [][]byte
// UpdateIDs are their record ids, deleted once a snapshot covers them.
UpdateIDs []string
// ContentJSON is pages.content_json, used to seed a page that predates collaboration.
ContentJSON json.RawMessage
// LastVersion is when the newest page version was taken (zero if none).
LastVersion time.Time
}
// Snapshot is a compacted document and what was derived from it.
type Snapshot struct {
State []byte
JSON []byte
Text string
LastEditor string
// Covers lists flushed update records that State already includes.
Covers []string
}
// Version is one entry of a page's history.
type Version struct {
ID string `json:"id"`
Author string `json:"author"`
Label string `json:"label"`
Created string `json:"created"`
}
// Store persists documents. PBStore is the real one; tests use a memory store.
type Store interface {
Load(ctx context.Context, page string) (Stored, error)
AppendUpdate(ctx context.Context, page string, update []byte) (id string, err error)
SaveSnapshot(ctx context.Context, page string, s Snapshot) error
AddVersion(ctx context.Context, page string, s Snapshot) error
// Content returns pages.content_json (null when never edited).
Content(ctx context.Context, page string) (json.RawMessage, error)
Versions(ctx context.Context, page string) ([]Version, error)
// VersionContent returns one version's ProseMirror JSON.
VersionContent(ctx context.Context, page, id string) (json.RawMessage, error)
}
type PBStore struct{ pb *pocketbase.Client }
func NewPBStore(pb *pocketbase.Client) *PBStore { return &PBStore{pb: pb} }
var b64 = base64.StdEncoding
func (s *PBStore) Load(ctx context.Context, page string) (Stored, error) {
var out Stored
ydoc, err := pocketbase.List[struct {
State string `json:"state"`
}](ctx, s.pb, "page_ydoc", pocketbase.ListOptions{PerPage: 1, Filter: fmt.Sprintf("page = '%s'", page), Fields: "state"})
if err != nil {
return out, err
}
if len(ydoc.Items) > 0 && ydoc.Items[0].State != "" {
if out.Snapshot, err = b64.DecodeString(ydoc.Items[0].State); err != nil {
return out, fmt.Errorf("page_ydoc %s: %w", page, err)
}
}
for n := 1; ; n++ {
res, err := pocketbase.List[struct {
ID string `json:"id"`
Update string `json:"update"`
}](ctx, s.pb, "page_yupdates", pocketbase.ListOptions{
Page: n, PerPage: 500, Filter: fmt.Sprintf("page = '%s'", page), Sort: "created,id", Fields: "id,update",
})
if err != nil {
return out, err
}
for _, r := range res.Items {
u, err := b64.DecodeString(r.Update)
if err != nil {
return out, fmt.Errorf("page_yupdates %s: %w", r.ID, err)
}
out.Updates = append(out.Updates, u)
out.UpdateIDs = append(out.UpdateIDs, r.ID)
}
if n >= res.TotalPages || len(res.Items) == 0 {
break
}
}
if out.Snapshot == nil && len(out.Updates) == 0 {
if out.ContentJSON, err = s.Content(ctx, page); err != nil {
return out, err
}
}
versions, err := pocketbase.List[struct {
Created string `json:"created"`
}](ctx, s.pb, "page_versions", pocketbase.ListOptions{PerPage: 1, Filter: fmt.Sprintf("page = '%s'", page), Sort: "-created", Fields: "created"})
if err != nil {
return out, err
}
if len(versions.Items) > 0 {
out.LastVersion, _ = time.Parse("2006-01-02 15:04:05.000Z", versions.Items[0].Created)
}
return out, nil
}
func (s *PBStore) AppendUpdate(ctx context.Context, page string, update []byte) (string, error) {
rec, err := pocketbase.Create[struct {
ID string `json:"id"`
}](ctx, s.pb, "page_yupdates", map[string]any{"page": page, "update": b64.EncodeToString(update)})
return rec.ID, err
}
func (s *PBStore) SaveSnapshot(ctx context.Context, page string, snap Snapshot) error {
existing, err := pocketbase.List[struct {
ID string `json:"id"`
}](ctx, s.pb, "page_ydoc", pocketbase.ListOptions{PerPage: 1, Filter: fmt.Sprintf("page = '%s'", page), Fields: "id"})
if err != nil {
return err
}
body := map[string]any{"page": page, "state": b64.EncodeToString(snap.State)}
type rec struct {
ID string `json:"id"`
}
if len(existing.Items) > 0 {
_, err = pocketbase.Update[rec](ctx, s.pb, "page_ydoc", existing.Items[0].ID, body)
} else {
_, err = pocketbase.Create[rec](ctx, s.pb, "page_ydoc", body)
}
if err != nil {
return err
}
patch := map[string]any{
"content_json": json.RawMessage(snap.JSON), "content_text": snap.Text, "word_count": len(strings.Fields(snap.Text)),
}
if snap.LastEditor != "" {
patch["last_editor"] = snap.LastEditor
}
if _, err := pocketbase.Update[rec](ctx, s.pb, "pages", page, patch); err != nil {
return err
}
for _, id := range snap.Covers {
if err := s.pb.Delete(ctx, "page_yupdates", id); err != nil && !pocketbase.IsNotFound(err) {
return err
}
}
return nil
}
func (s *PBStore) AddVersion(ctx context.Context, page string, snap Snapshot) error {
body := map[string]any{"page": page, "state": b64.EncodeToString(snap.State), "content_json": json.RawMessage(snap.JSON)}
if snap.LastEditor != "" {
body["author"] = snap.LastEditor
}
_, err := pocketbase.Create[struct {
ID string `json:"id"`
}](ctx, s.pb, "page_versions", body)
return err
}
func (s *PBStore) Content(ctx context.Context, page string) (json.RawMessage, error) {
rec, err := pocketbase.Get[struct {
ContentJSON json.RawMessage `json:"content_json"`
}](ctx, s.pb, "pages", page)
if err != nil {
return nil, err
}
return nullIfEmpty(rec.ContentJSON), nil
}
func (s *PBStore) Versions(ctx context.Context, page string) ([]Version, error) {
res, err := pocketbase.List[struct {
ID string `json:"id"`
Label string `json:"label"`
Created string `json:"created"`
Expand struct {
Author struct {
Name string `json:"name"`
Email string `json:"email"`
} `json:"author"`
} `json:"expand"`
}](ctx, s.pb, "page_versions", pocketbase.ListOptions{
PerPage: 200, Filter: fmt.Sprintf("page = '%s'", page), Sort: "-created",
Expand: "author", Fields: "id,label,created,expand.author.name,expand.author.email",
})
if err != nil {
return nil, err
}
out := make([]Version, 0, len(res.Items))
for _, r := range res.Items {
author := r.Expand.Author.Name
if author == "" {
author = r.Expand.Author.Email
}
out = append(out, Version{ID: r.ID, Author: author, Label: r.Label, Created: r.Created})
}
return out, nil
}
func (s *PBStore) VersionContent(ctx context.Context, page, id string) (json.RawMessage, error) {
res, err := pocketbase.List[struct {
ContentJSON json.RawMessage `json:"content_json"`
}](ctx, s.pb, "page_versions", pocketbase.ListOptions{
PerPage: 1, Filter: fmt.Sprintf("page = '%s' && id = '%s'", page, id), Fields: "content_json",
})
if err != nil {
return nil, err
}
if len(res.Items) == 0 {
return nil, ErrNotFound
}
return nullIfEmpty(res.Items[0].ContentJSON), nil
}
func nullIfEmpty(raw json.RawMessage) json.RawMessage {
if len(raw) == 0 || string(raw) == `""` {
return json.RawMessage("null")
}
return raw
}