Files
Docwell/Server/internal/search/scans.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

224 lines
5.5 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package search
// Scanned PDFs: a PDF attachment without a text layer goes on a queue
// instead of being read. When its workspace has AI read scans (ai/scans.go),
// ReadScans has the AI provider write it out, a few files per pass, and its
// page is indexed again with the text. Files wait on the queue while the
// workspace has it turned off, so turning it on later reads them too.
import (
"context"
"encoding/json"
"errors"
"strings"
"unicode/utf8"
"docwell/server/internal/store/pocketbase"
)
// ScanReader reads scanned PDFs for the index (the AI service).
type ScanReader interface {
// ReadsScans reports whether a workspace has its scanned PDFs read.
ReadsScans(ctx context.Context, workspace string) bool
// ReadScan writes out a scanned PDF's text, or returns the reader's
// "turned off" error (see UseScans) when the workspace does not read them.
ReadScan(ctx context.Context, workspace string, data []byte) (string, error)
}
// scanHook is the scan reader and its "turned off" error.
type scanHook struct {
r ScanReader
off error
}
// UseScans sets who reads scanned PDFs; without one they stay on the queue.
// off is the reader's "turned off" error.
func (x *Index) UseScans(r ScanReader, off error) {
x.scans.Store(&scanHook{r: r, off: off})
}
const scanQueueKey = "scanqueue"
const (
maxScanQueue = 5000 // files waiting; the oldest are dropped past this
scansPerPass = 5 // files read per pass
maxScanTries = 3 // failed reads before a file is given up on
scanFileLimit = 20 << 20 // larger scans are not sent
)
// scanEntry is one scanned PDF waiting to be read.
type scanEntry struct {
ID string `json:"id"`
Page string `json:"page"`
Workspace string `json:"workspace"`
Tries int `json:"tries,omitempty"`
}
func (x *Index) loadScans() ([]scanEntry, error) {
raw, err := x.idx.GetInternal([]byte(scanQueueKey))
if err != nil || len(raw) == 0 {
return nil, err
}
var q []scanEntry
if json.Unmarshal(raw, &q) != nil {
return nil, nil
}
return q, nil
}
func (x *Index) saveScans(q []scanEntry) error {
if len(q) > maxScanQueue {
q = q[len(q)-maxScanQueue:]
}
data, _ := json.Marshal(q)
return x.idx.SetInternal([]byte(scanQueueKey), data)
}
// queueScans adds scanned PDFs found by CatchUpFiles (x.mu held).
func (x *Index) queueScans(ctx context.Context, found []attachmentRow) error {
if len(found) == 0 {
return nil
}
q, err := x.loadScans()
if err != nil {
return err
}
have := map[string]bool{}
for _, e := range q {
have[e.ID] = true
}
for _, a := range found {
if have[a.ID] || a.Page == "" {
continue
}
p, err := pocketbase.Get[pageRow](ctx, x.pb, "pages", a.Page)
if err != nil {
continue
}
q = append(q, scanEntry{ID: a.ID, Page: a.Page, Workspace: p.Workspace})
have[a.ID] = true
}
return x.saveScans(q)
}
// ScansWaiting is how many scanned PDFs wait to be read.
func (x *Index) ScansWaiting() int {
x.mu.Lock()
defer x.mu.Unlock()
q, _ := x.loadScans()
return len(q)
}
// ReadScans reads a few queued scanned PDFs of workspaces that read scans,
// and indexes their pages again.
func (x *Index) ReadScans(ctx context.Context) error {
hook := x.scans.Load()
if hook == nil {
return nil
}
x.mu.Lock()
q, err := x.loadScans()
x.mu.Unlock()
if err != nil || len(q) == 0 {
return err
}
on := map[string]bool{}
done := map[string]bool{} // read, or gone: off the queue
failed := map[string]bool{} // tried again later, up to maxScanTries
read := map[string]fileText{}
pages := map[string]bool{}
n := 0
for _, e := range q {
if n >= scansPerPass || ctx.Err() != nil {
break
}
ok, seen := on[e.Workspace]
if !seen {
ok = hook.r.ReadsScans(ctx, e.Workspace)
on[e.Workspace] = ok
}
if !ok {
continue
}
n++
a, err := pocketbase.Get[attachmentRow](ctx, x.pb, "attachments", e.ID)
if err != nil {
if pocketbase.IsNotFound(err) {
done[e.ID] = true
} else {
failed[e.ID] = true
}
continue
}
data, ok := x.download(ctx, a, scanFileLimit)
if !ok {
failed[e.ID] = true
continue
}
if data == nil { // too large to send
done[e.ID] = true
continue
}
text, err := hook.r.ReadScan(ctx, e.Workspace, data)
switch {
case hook.off != nil && errors.Is(err, hook.off):
on[e.Workspace] = false
case err != nil:
x.log.Warn("search: reading a scanned PDF", "id", e.ID, "err", err)
failed[e.ID] = true
default:
read[e.ID] = fileText{Name: a.Name, Text: cleanText(text)}
done[e.ID] = true
if a.Page != "" {
pages[a.Page] = true
}
}
}
if len(done) == 0 && len(failed) == 0 {
return nil
}
x.mu.Lock()
defer x.mu.Unlock()
// The queue may have grown meanwhile: apply the results to the current one.
cur, err := x.loadScans()
if err != nil {
return err
}
next := make([]scanEntry, 0, len(cur))
for _, e := range cur {
if done[e.ID] {
continue
}
if failed[e.ID] {
if e.Tries++; e.Tries >= maxScanTries {
continue
}
}
next = append(next, e)
}
batch := x.idx.NewBatch()
for id, ft := range read {
data, _ := json.Marshal(ft)
batch.SetInternal(fileTextKey(id), data)
}
if err := x.idx.Batch(batch); err != nil {
return err
}
if err := x.saveScans(next); err != nil {
return err
}
return x.reindexPages(ctx, pages)
}
// cleanText is file text as the index keeps it: spaces folded, length capped.
func cleanText(text string) string {
text = strings.Join(strings.Fields(text), " ")
if utf8.RuneCountInString(text) > maxFileText {
text = string([]rune(text)[:maxFileText])
}
return text
}