Files
Docwell/Server/internal/search/search.go
T
tajniak81andClaude Opus 5.5 ffc6cc4fbc Build out the admin panel
- Overview: users, organizations, workspaces, spaces, pages, files and
  storage (org admins see their organization), plus pages open right now,
  the search index size, and version, uptime and database health.
- Users: invite people by email (with resend, revoke and a copyable link
  when mail fails) and send a password-reset email.
- Authentication: sign-up on or off, the email-domain allow-list, and
  sign-in links by email.
- Branding: instance name, accent colour and logo. The web app shows them
  on the sign-in pages and applies the accent colour everywhere.
- Email and Storage: SMTP and S3 settings with test buttons.
- Maintenance: create, download and delete database backups, and a view
  of the background jobs with their last run, duration and errors.

On the server, a small jobs registry records each search-indexing pass,
and "search.rebuild" replaces the separate reindex endpoint. A new
instance package serves the dashboard numbers, health and backups.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 17:34:48 +01:00

365 lines
11 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
// Package search keeps a Bleve full-text index of page titles and text.
//
// The index follows PocketBase instead of being told about every change: an
// indexer polls for pages whose "updated" moved since its checkpoint (titles,
// saved content, trash and restore all touch it) and, now and then, sweeps out
// pages that were deleted for good. The index can always be thrown away and
// rebuilt from PocketBase, so it lives in a plain directory without backups.
package search
import (
"context"
"errors"
"fmt"
"log/slog"
"math"
"os"
"path/filepath"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/blevesearch/bleve/v2"
"github.com/blevesearch/bleve/v2/analysis/analyzer/keyword"
"github.com/blevesearch/bleve/v2/analysis/analyzer/standard"
"github.com/blevesearch/bleve/v2/mapping"
"github.com/blevesearch/bleve/v2/search/query"
"docwell/server/internal/store/pocketbase"
)
// doc is what the index stores per page.
type doc struct {
Workspace string `json:"workspace"`
Space string `json:"space"`
Title string `json:"title"`
Icon string `json:"icon"`
Text string `json:"text"`
Updated string `json:"updated"`
}
// Hit is one search result. Highlights are [start, end) rune offsets of the
// matched words in Snippet, so clients can mark them without parsing HTML.
type Hit struct {
ID string `json:"id"`
Title string `json:"title"`
Icon string `json:"icon"`
Space string `json:"space"`
Snippet string `json:"snippet"`
Highlights [][2]int `json:"highlights"`
Updated string `json:"updated"`
}
type Index struct {
idx bleve.Index
pb *pocketbase.Client
log *slog.Logger
mu sync.Mutex // serializes indexing passes
track func(name string, fn func() error) error
}
// Track reports each indexing pass to fn (the admin panel's job list).
func (x *Index) Track(fn func(name string, run func() error) error) { x.track = fn }
func (x *Index) tracked(name string, fn func() error) error {
if x.track == nil {
return fn()
}
return x.track(name, fn)
}
const checkpointKey = "checkpoint"
func newMapping() mapping.IndexMapping {
keywordField := bleve.NewKeywordFieldMapping()
keywordField.Analyzer = keyword.Name
stored := bleve.NewTextFieldMapping()
stored.Index = false
text := bleve.NewTextFieldMapping()
text.Analyzer = standard.Name
text.IncludeTermVectors = true
page := bleve.NewDocumentMapping()
page.AddFieldMappingsAt("workspace", keywordField)
page.AddFieldMappingsAt("space", keywordField)
page.AddFieldMappingsAt("title", text)
page.AddFieldMappingsAt("text", text)
page.AddFieldMappingsAt("icon", stored)
page.AddFieldMappingsAt("updated", stored)
m := bleve.NewIndexMapping()
m.DefaultMapping = page
m.DefaultAnalyzer = standard.Name
return m
}
// Open opens the index in dir, creating it when missing. An index that cannot
// be opened (corrupt, or from an incompatible version) is rebuilt.
func Open(dir string, pb *pocketbase.Client, log *slog.Logger) (*Index, error) {
path := filepath.Join(dir, "search.bleve")
idx, err := bleve.Open(path)
if errors.Is(err, bleve.ErrorIndexPathDoesNotExist) {
if err := os.MkdirAll(dir, 0o750); err != nil {
return nil, err
}
idx, err = bleve.New(path, newMapping())
} else if err != nil {
log.Warn("search: rebuilding unreadable index", "err", err)
if rmErr := os.RemoveAll(path); rmErr != nil {
return nil, rmErr
}
idx, err = bleve.New(path, newMapping())
}
if err != nil {
return nil, fmt.Errorf("search index %s: %w", path, err)
}
return &Index{idx: idx, pb: pb, log: log}, nil
}
// OpenMemory opens an in-memory index (tests).
func OpenMemory(pb *pocketbase.Client, log *slog.Logger) (*Index, error) {
idx, err := bleve.NewMemOnly(newMapping())
if err != nil {
return nil, err
}
return &Index{idx: idx, pb: pb, log: log}, nil
}
func (x *Index) Close() error { return x.idx.Close() }
// Count is the number of indexed pages.
func (x *Index) Count() (uint64, error) { return x.idx.DocCount() }
// Put indexes or re-indexes one page.
func (x *Index) Put(id string, d doc) error { return x.idx.Index(id, d) }
// Remove drops one page.
func (x *Index) Remove(id string) error { return x.idx.Delete(id) }
// Run keeps the index up to date until ctx ends: catch-up every interval,
// a sweep for deleted pages every sweepEvery.
func (x *Index) Run(ctx context.Context, interval, sweepEvery time.Duration) {
tick := time.NewTicker(interval)
defer tick.Stop()
lastSweep := time.Time{}
for {
if err := x.tracked("search.index", func() error { return x.CatchUp(ctx) }); err != nil && ctx.Err() == nil {
x.log.Warn("search: indexing failed", "err", err)
}
if time.Since(lastSweep) >= sweepEvery {
if err := x.tracked("search.sweep", func() error { return x.Sweep(ctx) }); err != nil && ctx.Err() == nil {
x.log.Warn("search: sweep failed", "err", err)
}
lastSweep = time.Now()
}
select {
case <-ctx.Done():
return
case <-tick.C:
}
}
}
type pageRow struct {
ID string `json:"id"`
Workspace string `json:"workspace"`
Space string `json:"space"`
Title string `json:"title"`
Icon string `json:"icon"`
ContentText string `json:"content_text"`
DeletedAt string `json:"deleted_at"`
Updated string `json:"updated"`
}
// CatchUp indexes every page that changed since the checkpoint.
func (x *Index) CatchUp(ctx context.Context) error {
x.mu.Lock()
defer x.mu.Unlock()
raw, err := x.idx.GetInternal([]byte(checkpointKey))
if err != nil {
return err
}
checkpoint := string(raw)
for {
// >= because several pages can share a millisecond; re-indexing is harmless.
filter := ""
if checkpoint != "" {
filter = fmt.Sprintf("updated >= '%s'", checkpoint)
}
res, err := pocketbase.List[pageRow](ctx, x.pb, "pages", pocketbase.ListOptions{
PerPage: 200, Filter: filter, Sort: "updated,id",
Fields: "id,workspace,space,title,icon,content_text,deleted_at,updated",
})
if err != nil {
return err
}
batch := x.idx.NewBatch()
for _, p := range res.Items {
if p.DeletedAt != "" {
// Trashed pages are not searchable; a restore touches "updated" again.
batch.Delete(p.ID)
continue
}
if err := batch.Index(p.ID, doc{
Workspace: p.Workspace, Space: p.Space, Title: p.Title, Icon: p.Icon, Text: p.ContentText, Updated: p.Updated,
}); err != nil {
return err
}
}
next := checkpoint
if n := len(res.Items); n > 0 {
next = res.Items[n-1].Updated
}
batch.SetInternal([]byte(checkpointKey), []byte(next))
if err := x.idx.Batch(batch); err != nil {
return err
}
// Stop when a page is short, or when a full page all shares the checkpoint
// (otherwise the >= filter would return the same rows forever).
if len(res.Items) < 200 || next == checkpoint {
return nil
}
checkpoint = next
}
}
// Sweep removes pages that no longer exist in PocketBase (purged pages, and
// pages of deleted spaces and workspaces, which cascade without a trace).
func (x *Index) Sweep(ctx context.Context) error {
x.mu.Lock()
defer x.mu.Unlock()
live := map[string]bool{}
for page := 1; ; page++ {
res, err := pocketbase.List[struct {
ID string `json:"id"`
}](ctx, x.pb, "pages", pocketbase.ListOptions{Page: page, PerPage: 1000, Fields: "id", Filter: "deleted_at = ''"})
if err != nil {
return err
}
for _, p := range res.Items {
live[p.ID] = true
}
if page >= res.TotalPages || len(res.Items) == 0 {
break
}
}
req := bleve.NewSearchRequestOptions(bleve.NewMatchAllQuery(), 1000, 0, false)
batch := x.idx.NewBatch()
for from := 0; ; from += 1000 {
req.From = from
res, err := x.idx.SearchInContext(ctx, req)
if err != nil {
return err
}
for _, h := range res.Hits {
if !live[h.ID] {
batch.Delete(h.ID)
}
}
if len(res.Hits) < 1000 {
break
}
}
if batch.Size() == 0 {
return nil
}
return x.idx.Batch(batch)
}
// Rebuild forgets the checkpoint, so the next pass re-indexes everything,
// and runs it now.
func (x *Index) Rebuild(ctx context.Context) error {
x.mu.Lock()
err := x.idx.SetInternal([]byte(checkpointKey), nil)
x.mu.Unlock()
if err != nil {
return err
}
if err := x.CatchUp(ctx); err != nil {
return err
}
return x.Sweep(ctx)
}
// Query searches the pages of workspace inside spaces (the caller's visible
// spaces). An empty spaces list finds nothing.
func (x *Index) Query(ctx context.Context, workspace string, spaces []string, text string, limit int) ([]Hit, int, error) {
text = strings.TrimSpace(text)
if text == "" || len(spaces) == 0 {
return []Hit{}, 0, nil
}
if len(text) > 200 {
text = text[:200]
}
ws := bleve.NewTermQuery(workspace)
ws.SetField("workspace")
var inSpace []query.Query
for _, s := range spaces {
q := bleve.NewTermQuery(s)
q.SetField("space")
inSpace = append(inSpace, q)
}
// Words match in the title (worth more) or the text; the last word also
// matches as a prefix, so results appear while typing.
var match []query.Query
for field, boost := range map[string]float64{"title": 3, "text": 1} {
m := bleve.NewMatchQuery(text)
m.SetField(field)
m.SetBoost(boost)
match = append(match, m)
fuzzy := bleve.NewMatchQuery(text)
fuzzy.SetField(field)
fuzzy.SetFuzziness(1)
fuzzy.SetBoost(boost / 4)
match = append(match, fuzzy)
}
words := strings.Fields(strings.ToLower(text))
if last := words[len(words)-1]; utf8.RuneCountInString(last) >= 2 {
for field, boost := range map[string]float64{"title": 2, "text": 0.5} {
p := bleve.NewPrefixQuery(last)
p.SetField(field)
p.SetBoost(boost)
match = append(match, p)
}
}
q := bleve.NewConjunctionQuery(ws, bleve.NewDisjunctionQuery(inSpace...), bleve.NewDisjunctionQuery(match...))
req := bleve.NewSearchRequestOptions(q, max(1, min(limit, 50)), 0, false)
req.Fields = []string{"title", "icon", "space", "text", "updated"}
req.IncludeLocations = true
res, err := x.idx.SearchInContext(ctx, req)
if err != nil {
return nil, 0, err
}
hits := make([]Hit, 0, len(res.Hits))
for _, h := range res.Hits {
str := func(k string) string { s, _ := h.Fields[k].(string); return s }
var spans [][2]int
for _, locs := range h.Locations["text"] {
for _, l := range locs {
spans = append(spans, [2]int{toInt(l.Start), toInt(l.End)})
}
}
snippet, marks := Snippet(str("text"), spans, 160)
hits = append(hits, Hit{
ID: h.ID, Title: str("title"), Icon: str("icon"), Space: str("space"),
Snippet: snippet, Highlights: marks, Updated: str("updated"),
})
}
return hits, toInt(res.Total), nil
}
// toInt converts Bleve's counts and offsets, which are far below MaxInt32 in practice.
func toInt(u uint64) int {
if u > math.MaxInt32 {
return math.MaxInt32
}
return int(u)
}