// SPDX-License-Identifier: AGPL-3.0-or-later 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 // Unversioned is true when the saved document changed after the newest version. Unversioned bool } // Snapshot is a compacted document and what was derived from it. type Snapshot struct { State []byte JSON []byte Text string LastEditor string // Label names a version (AddVersion only). Label 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 // pbTime is how PocketBase formats dates. const pbTime = "2006-01-02 15:04:05.000Z" func (s *PBStore) Load(ctx context.Context, page string) (Stored, error) { var out Stored ydoc, err := pocketbase.List[struct { State string `json:"state"` Updated string `json:"updated"` }](ctx, s.pb, "page_ydoc", pocketbase.ListOptions{PerPage: 1, Filter: fmt.Sprintf("page = '%s'", page), Fields: "state,updated"}) 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(pbTime, versions.Items[0].Created) } // A saved document newer than the newest version (or pending updates) still needs one. out.Unversioned = len(out.Updates) > 0 if len(ydoc.Items) > 0 { saved, _ := time.Parse(pbTime, ydoc.Items[0].Updated) out.Unversioned = out.Unversioned || saved.After(out.LastVersion) } 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 } type rec struct { ID string `json:"id"` } // The page first: for a deleted page this fails with ErrNotFound. 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 notFound(err) } body := map[string]any{"page": page, "state": b64.EncodeToString(snap.State)} 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 } 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), "label": snap.Label, } 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, notFound(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 notFound(err error) error { if pocketbase.IsNotFound(err) { return ErrNotFound } return err } func nullIfEmpty(raw json.RawMessage) json.RawMessage { if len(raw) == 0 || string(raw) == `""` { return json.RawMessage("null") } return raw }