Files
Docwell/Server/internal/search/search.go
T
tajniak81andClaude Opus 5.5 c98b127f1e
CI / go (Media) (push) Successful in 13m40s
CI / go (Server) (push) Failing after 23m20s
CI / go (Web-App) (push) Canceled after 0s
CI / frontend (push) Failing after 10m35s
Docs / build (push) Canceled after 0s
Docs / deploy (push) Canceled after 0s
CI / desktop (ubuntu-latest) (push) Failing after 3h4m42s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
CI / mobile (push) Failing after 9m19s
CI / docker (push) Successful in 2h2m57s
Add columns, suggesting mode, verified pages, scanned PDF search and server translations
- Columns: /columns puts 2 to 4 columns side by side, with widths dragged
  between them; they stack on phones. HTML export and import keep them
  (also Notion column lists and Confluence page layouts).
- Suggesting mode: edits become suggested insertions and deletions that
  editors accept or reject one by one or all at once. Text only.
- Verified pages: editors verify a page for a while or without end; the
  verifier is notified when it runs out (migration 1764700000).
- Scanned PDFs attached to pages are read by AI for search where a
  workspace turns it on.
- The server writes error messages, emails, digests and phone
  notifications in English, Polish, German, French and Spanish; the apps
  send their language with each request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 08:38:08 +01:00

596 lines
18 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
// Package search keeps a Bleve full-text index of page titles and text, of
// the records of the databases in them (ADR-13), and of the text of the
// files attached to them (files.go): a record or a file is its own document,
// so a search can say what it found rather than only its page.
//
// 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"
"encoding/json"
"errors"
"fmt"
"log/slog"
"math"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"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/convert"
"docwell/server/internal/store/pocketbase"
)
// doc is what the index stores per page, or per database record. Modified is
// Updated parsed, so searches can be limited to a time range. A record
// (Kind "record") has its own title and text and the rest from its page.
type doc struct {
Kind string `json:"kind,omitempty"`
Page string `json:"page,omitempty"`
PageTitle string `json:"pageTitle,omitempty"`
Database string `json:"database,omitempty"`
Row string `json:"row,omitempty"`
File string `json:"file,omitempty"`
Workspace string `json:"workspace"`
Space string `json:"space"`
Title string `json:"title"`
Icon string `json:"icon"`
Text string `json:"text"`
Creator string `json:"creator"`
Editor string `json:"editor"`
Updated string `json:"updated"`
Modified time.Time `json:"modified"`
}
// Filter narrows a search. Zero fields do not filter.
type Filter struct {
Author string // created or last edited the page
After, Before time.Time
}
func (f Filter) empty() bool { return f.Author == "" && f.After.IsZero() && f.Before.IsZero() }
const pbTimeLayout = "2006-01-02 15:04:05.000Z"
func newDoc(p pageRow) doc {
modified, _ := time.Parse(pbTimeLayout, p.Updated)
return doc{
Workspace: p.Workspace, Space: p.Space, Title: p.Title, Icon: p.Icon, Text: p.ContentText,
Creator: p.Creator, Editor: p.LastEditor, Updated: p.Updated, Modified: modified,
}
}
const recordKind = "record"
// recordDocs are the documents of the records in a page's databases, by id.
func recordDocs(p pageRow) map[string]doc {
recs, err := convert.Records(p.ContentJSON)
if err != nil || len(recs) == 0 {
return nil
}
page := newDoc(p)
out := make(map[string]doc, len(recs))
for _, r := range recs {
d := page
d.Kind, d.Page, d.PageTitle, d.Database, d.Row = recordKind, p.ID, p.Title, r.Database, r.Row
d.Title, d.Text = r.Title, r.Text
out[p.ID+":"+r.Database+":"+r.Row] = d
}
return out
}
// RecordHit names the database record a hit found, inside the hit's page.
type RecordHit struct {
Database string `json:"database"`
Row string `json:"row"`
Title string `json:"title"`
}
// Hit is one search result: a page, or a record in it (Record set; ID is
// still the page's). 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"`
Record *RecordHit `json:"record,omitempty"`
File *FileHit `json:"file,omitempty"`
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
// scans reads scanned PDFs (scans.go); set once the AI service is up.
scans atomic.Pointer[scanHook]
}
// 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"
// mappingKey holds mappingVersion; an index built with another mapping is
// rebuilt on open. Bump the version whenever newMapping changes.
mappingKey = "mapping"
mappingVersion = "4"
)
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("creator", keywordField)
page.AddFieldMappingsAt("editor", keywordField)
page.AddFieldMappingsAt("kind", keywordField)
page.AddFieldMappingsAt("page", keywordField)
page.AddFieldMappingsAt("modified", bleve.NewDateTimeFieldMapping())
page.AddFieldMappingsAt("title", text)
page.AddFieldMappingsAt("text", text)
page.AddFieldMappingsAt("icon", stored)
page.AddFieldMappingsAt("updated", stored)
page.AddFieldMappingsAt("pageTitle", stored)
page.AddFieldMappingsAt("database", stored)
page.AddFieldMappingsAt("row", stored)
page.AddFieldMappingsAt("file", 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) or that was built with
// an older mapping 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 err == nil {
if v, vErr := idx.GetInternal([]byte(mappingKey)); vErr != nil || string(v) != mappingVersion {
_ = idx.Close()
err = errors.New("built with an older mapping")
}
}
if errors.Is(err, bleve.ErrorIndexPathDoesNotExist) {
if err := os.MkdirAll(dir, 0o750); err != nil {
return nil, err
}
idx, err = createIndex(path)
} else if err != nil {
log.Warn("search: rebuilding unreadable index", "err", err)
if rmErr := os.RemoveAll(path); rmErr != nil {
return nil, rmErr
}
idx, err = createIndex(path)
}
if err != nil {
return nil, fmt.Errorf("search index %s: %w", path, err)
}
return &Index{idx: idx, pb: pb, log: log}, nil
}
func createIndex(path string) (bleve.Index, error) {
idx, err := bleve.New(path, newMapping())
if err != nil {
return nil, err
}
if err := idx.SetInternal([]byte(mappingKey), []byte(mappingVersion)); err != nil {
_ = idx.Close()
return nil, err
}
return idx, 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 (records and files not counted).
func (x *Index) Count() (uint64, error) {
q := bleve.NewBooleanQuery()
q.AddMust(bleve.NewMatchAllQuery())
q.AddMustNot(isChild())
res, err := x.idx.Search(bleve.NewSearchRequestOptions(q, 0, 0, false))
if err != nil {
return 0, err
}
return res.Total, nil
}
// isChild matches the documents inside a page: records and files.
func isChild() query.Query {
var kinds []query.Query
for _, k := range []string{recordKind, fileKind} {
q := bleve.NewTermQuery(k)
q.SetField("kind")
kinds = append(kinds, q)
}
return bleve.NewDisjunctionQuery(kinds...)
}
// recordsKey is where the index keeps the ids of a page's record documents,
// to drop the ones whose records were deleted.
func recordsKey(page string) []byte { return []byte("records/" + page) }
// indexPage adds a page with its records and files to batch, dropping the
// ones it no longer has; a trashed page goes with all of them.
func (x *Index) indexPage(batch *bleve.Batch, p pageRow) error {
var old []string
raw, err := x.idx.GetInternal(recordsKey(p.ID))
if err != nil {
return err
}
if len(raw) > 0 {
old = strings.Split(string(raw), " ")
}
var recs map[string]doc
if p.DeletedAt != "" {
// Trashed pages are not searchable; a restore touches "updated" again.
batch.Delete(p.ID)
} else {
if err := batch.Index(p.ID, newDoc(p)); err != nil {
return err
}
recs = recordDocs(p)
files, err := x.fileDocs(p)
if err != nil {
return err
}
if recs == nil && len(files) > 0 {
recs = map[string]doc{}
}
for id, d := range files {
recs[id] = d
}
}
for _, id := range old {
if _, ok := recs[id]; !ok {
batch.Delete(id)
}
}
ids := make([]string, 0, len(recs))
for id, d := range recs {
if err := batch.Index(id, d); err != nil {
return err
}
ids = append(ids, id)
}
if len(ids) > 0 {
batch.SetInternal(recordsKey(p.ID), []byte(strings.Join(ids, " ")))
} else if len(old) > 0 {
batch.DeleteInternal(recordsKey(p.ID))
}
return nil
}
// 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, lastScans := time.Time{}, 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 err := x.tracked("search.files", func() error { return x.CatchUpFiles(ctx) }); err != nil && ctx.Err() == nil {
x.log.Warn("search: reading attachments failed", "err", err)
}
if x.scans.Load() != nil && time.Since(lastScans) >= time.Minute {
if err := x.tracked("search.scans", func() error { return x.ReadScans(ctx) }); err != nil && ctx.Err() == nil {
x.log.Warn("search: reading scanned PDFs failed", "err", err)
}
lastScans = time.Now()
}
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"`
ContentJSON json.RawMessage `json:"content_json"`
Creator string `json:"creator"`
LastEditor string `json:"last_editor"`
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,content_json,creator,last_editor,deleted_at,updated",
})
if err != nil {
return err
}
batch := x.idx.NewBatch()
for _, p := range res.Items {
if err := x.indexPage(batch, p); 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 {
// A record's id starts with its page's.
page, _, isRec := strings.Cut(h.ID, ":")
if !live[page] {
batch.Delete(h.ID)
if !isRec {
batch.DeleteInternal(recordsKey(page))
}
}
}
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)
if err == nil {
// Files already read keep their text; the others are tried again.
err = x.idx.SetInternal([]byte(fileCheckpointKey), nil)
}
x.mu.Unlock()
if err != nil {
return err
}
if err := x.CatchUpFiles(ctx); 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. Empty text with a non-empty
// filter lists the matching pages, most recently changed first.
func (x *Index) Query(ctx context.Context, workspace string, spaces []string, text string, f Filter, limit int) ([]Hit, int, error) {
text = strings.TrimSpace(text)
if (text == "" && f.empty()) || 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)
}
must := []query.Query{ws, bleve.NewDisjunctionQuery(inSpace...)}
if f.Author != "" {
var by []query.Query
for _, field := range []string{"creator", "editor"} {
q := bleve.NewTermQuery(f.Author)
q.SetField(field)
by = append(by, q)
}
must = append(must, bleve.NewDisjunctionQuery(by...))
}
if !f.After.IsZero() || !f.Before.IsZero() {
inclusive := true
q := bleve.NewDateRangeInclusiveQuery(f.After, f.Before, &inclusive, &inclusive)
q.SetField("modified")
must = append(must, q)
}
q := bleve.NewBooleanQuery()
if text != "" {
must = append(must, textQuery(text))
} else {
// Listing by filter alone lists pages, not every record in them.
q.AddMustNot(isChild())
}
q.AddMust(must...)
req := bleve.NewSearchRequestOptions(q, max(1, min(limit, 50)), 0, false)
req.Fields = []string{"title", "icon", "space", "text", "updated", "kind", "page", "pageTitle", "database", "row", "file"}
req.IncludeLocations = true
if text == "" {
req.SortBy([]string{"-modified", "_id"})
}
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)
hit := Hit{
ID: h.ID, Title: str("title"), Icon: str("icon"), Space: str("space"),
Snippet: snippet, Highlights: marks, Updated: str("updated"),
}
switch str("kind") {
case recordKind:
hit.ID, hit.Title = str("page"), str("pageTitle")
hit.Record = &RecordHit{Database: str("database"), Row: str("row"), Title: str("title")}
case fileKind:
hit.ID, hit.Title = str("page"), str("pageTitle")
hit.File = &FileHit{ID: str("file"), Name: str("title")}
}
hits = append(hits, hit)
}
return hits, toInt(res.Total), nil
}
// textQuery matches words in the title (worth more) or the text; the last
// word also matches as a prefix, so results appear while typing.
func textQuery(text string) query.Query {
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)
}
}
return bleve.NewDisjunctionQuery(match...)
}
// 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)
}