Add full-text search with Bleve and the Ctrl+K palette

docwell-server keeps a Bleve index of page titles and text in
DOCWELL_DATA_DIR. Instead of hooking every write, an indexer polls
PocketBase for pages whose "updated" moved (titles, saved content, trash
and restore all touch it) and sweeps out purged pages every ten minutes.
The index can be thrown away at any time: it rebuilds from the database,
and superadmins can trigger a rebuild.

Searches are limited to the spaces the caller can open, match the last
word as a prefix and forgive one wrong letter. Snippets come back as
plain text with match offsets, so clients never render server HTML.

In the web app, Ctrl+K or the sidebar's search box opens a palette that
shows recent pages until something is typed.

The server containers get a /data volume for the index.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-10-31 16:57:55 +01:00
1 parent e49b1ab34f
commit 25e7ca19a5
27 files changed
+1191 -7

No files matched your search

+2
View File
@@ -18,6 +18,8 @@ build/bin/
# PocketBase local data
pb_data/
# docwell-server's search index (DOCWELL_DATA_DIR) during local development
Server/data/
/Database/bin/
# Env and editor
+4 -2
View File
@@ -43,9 +43,11 @@ COPY --from=build /out/ /usr/local/bin/
COPY Database/pb_migrations /pb_migrations
COPY Database/pb_hooks /pb_hooks
COPY Docker-AIO/start.sh /start.sh
RUN chmod +x /start.sh
RUN chmod +x /start.sh && mkdir /data
VOLUME /pb_data
# /data holds the search index, which is rebuilt from PocketBase when missing.
ENV DOCWELL_DATA_DIR=/data
VOLUME /pb_data /data
EXPOSE 3000
HEALTHCHECK --interval=10s --timeout=3s --retries=5 \
CMD wget -qO- http://127.0.0.1:3000/api/v1/version >/dev/null || exit 1
+2
View File
@@ -25,8 +25,10 @@ services:
DOCWELL_MAIL_FROM: ${DOCWELL_MAIL_FROM:-no-reply@docwell.localhost}
volumes:
- pb_data:/pb_data
- server_data:/data
ports:
- "3000:3000"
volumes:
pb_data:
server_data:
+4
View File
@@ -44,6 +44,9 @@ services:
# Defaults until a superadmin saves signup rules in the admin panel.
DOCWELL_SIGNUP_ENABLED: ${DOCWELL_SIGNUP_ENABLED:-true}
DOCWELL_SIGNUP_DOMAINS: ${DOCWELL_SIGNUP_DOMAINS:-}
volumes:
# The search index (rebuilt from the database when missing).
- server_data:/data
ports:
- "8080:8080"
@@ -71,3 +74,4 @@ services:
volumes:
pb_data:
server_data:
+5
View File
@@ -36,6 +36,8 @@ export type Invite = Schemas["Invite"];
export type Group = Schemas["Group"];
export type PageItem = Schemas["PageItem"];
export type Attachment = Schemas["Attachment"];
export type SearchHit = Schemas["SearchHit"];
export type SearchResult = Schemas["SearchResult"];
export type GroupRequest = Schemas["GroupRequest"];
export type SpaceGroup = Schemas["SpaceGroup"];
export type MemberUser = Schemas["MemberUser"];
@@ -167,6 +169,7 @@ export function createClient(opts: ClientOptions) {
update: (patch: InstanceSettingsUpdate) => request<InstanceSettings>("PATCH", "/api/v1/admin/settings", patch),
testEmail: (to: string) => post("/api/v1/admin/settings/test-email", { to }),
testStorage: () => post("/api/v1/admin/settings/test-storage"),
reindexSearch: () => post("/api/v1/admin/search/reindex"),
},
users: {
@@ -203,6 +206,8 @@ export function createClient(opts: ClientOptions) {
createSpace: (id: string, input: CreateSpaceRequest) =>
post<Space>(`/api/v1/workspaces/${encodeURIComponent(id)}/spaces`, input),
groups: (id: string) => request<Group[]>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/groups`),
search: (id: string, q: string, limit?: number) =>
request<SearchResult>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/search${query({ q, limit })}`),
favorites: (id: string) => request<PageItem[]>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/favorites`),
recent: (id: string, limit?: number) =>
request<PageItem[]>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/recent${query({ limit })}`),
+100
View File
@@ -1124,6 +1124,45 @@ export interface paths {
patch?: never;
trace?: never;
};
"/api/v1/workspaces/{id}/search": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
/**
* Full-text search of page titles and text, in the spaces the caller can open
* @description Trashed pages are not found. The index catches up with edits within a few seconds.
*/
get: operations["searchPages"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/admin/search/reindex": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/** Rebuild the search index from the database (superadmin) */
post: operations["reindexSearch"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
}
export type webhooks = Record<string, never>;
export interface components {
@@ -1488,6 +1527,22 @@ export interface components {
url: string;
created: string;
};
SearchHit: {
id: string;
title: string;
icon: string;
space: string;
spaceName: string;
/** @description Plain text around the first match */
snippet: string;
/** @description [start, end) character offsets of matches in snippet */
highlights: number[][];
updated: string;
};
SearchResult: {
items: components["schemas"]["SearchHit"][];
total: number;
};
};
responses: {
/** @description Signed in */
@@ -3538,4 +3593,49 @@ export interface operations {
404: components["responses"]["Error"];
};
};
searchPages: {
parameters: {
query: {
q: string;
limit?: number;
};
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["SearchResult"];
};
};
404: components["responses"]["Error"];
};
};
reindexSearch: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Started */
202: {
headers: {
[name: string]: unknown;
};
content?: never;
};
403: components["responses"]["Error"];
};
};
}
+75
View File
@@ -1655,3 +1655,78 @@ class Attachment {
'created': created,
};
}
class SearchHit {
const SearchHit({
required this.id,
required this.title,
required this.icon,
required this.space,
required this.spaceName,
required this.snippet,
required this.highlights,
required this.updated,
});
factory SearchHit.fromJson(Map<String, dynamic> json) => SearchHit(
id: json['id'] as String,
title: json['title'] as String,
icon: json['icon'] as String,
space: json['space'] as String,
spaceName: json['spaceName'] as String,
snippet: json['snippet'] as String,
highlights: (json['highlights'] as List)
.map((e) => (e as List).map((e) => (e as num).toInt()).toList())
.toList(),
updated: json['updated'] as String,
);
final String id;
final String title;
final String icon;
final String space;
final String spaceName;
/// Plain text around the first match
final String snippet;
/// [start, end) character offsets of matches in snippet
final List<List<int>> highlights;
final String updated;
Map<String, dynamic> toJson() => {
'id': id,
'title': title,
'icon': icon,
'space': space,
'spaceName': spaceName,
'snippet': snippet,
'highlights': highlights.map((e) => e.map((e) => e).toList()).toList(),
'updated': updated,
};
}
class SearchResult {
const SearchResult({required this.items, required this.total});
factory SearchResult.fromJson(Map<String, dynamic> json) => SearchResult(
items: (json['items'] as List)
.map((e) => SearchHit.fromJson(e as Map<String, dynamic>))
.toList(),
total: (json['total'] as num).toInt(),
);
final List<SearchHit> items;
final int total;
Map<String, dynamic> toJson() => {
'items': items.map((e) => e.toJson()).toList(),
'total': total,
};
}
+4 -1
View File
@@ -28,9 +28,12 @@ RUN CGO_ENABLED=0 GOWORK=off go build -trimpath -ldflags "-s -w -X main.Version=
-o /out/docwell-server ./cmd/docwell-server
FROM alpine:3.22
RUN apk add --no-cache ca-certificates && adduser -D -u 10001 docwell
RUN apk add --no-cache ca-certificates && adduser -D -u 10001 docwell && mkdir /data && chown docwell /data
COPY --from=build /out/docwell-server /usr/local/bin/docwell-server
USER docwell
# The search index; it is rebuilt from PocketBase when missing.
ENV DOCWELL_DATA_DIR=/data
VOLUME /data
EXPOSE 8080
HEALTHCHECK --interval=10s --timeout=3s --retries=5 \
CMD wget -qO- http://127.0.0.1:8080/healthz >/dev/null || exit 1
+12
View File
@@ -22,6 +22,7 @@ import (
"docwell/server/internal/directory"
"docwell/server/internal/httpapi"
"docwell/server/internal/mail"
"docwell/server/internal/search"
"docwell/server/internal/settings"
"docwell/server/internal/store/pocketbase"
"docwell/server/internal/ycrdt"
@@ -65,6 +66,16 @@ func run(log *slog.Logger) error {
Store: collab.NewPBStore(db), Docs: ycrdt.NewPool(yrs, max(2, runtime.GOMAXPROCS(0))), Log: log,
})
dirSvc := directory.New(db, authSvc.Forget, hub)
// The search index follows PocketBase and can be rebuilt from it at any time.
index, err := search.Open(cfg.DataDir, db, log)
if err != nil {
return err
}
defer index.Close()
indexCtx, stopIndex := context.WithCancel(context.Background())
defer stopIndex()
go index.Run(indexCtx, 3*time.Second, 10*time.Minute)
dirSvc.UseSearch(index)
dirSvc.SetMaxUpload(int64(cfg.MaxUploadMB) << 20)
dirSvc.UseMail(directory.Mailer{Sender: mailer, WebURL: cfg.WebURL, AppName: func(ctx context.Context) string {
b, _ := settingsSvc.Branding(ctx)
@@ -84,6 +95,7 @@ func run(log *slog.Logger) error {
// without another secret to configure.
FileTokens: auth.NewFileTokens(cfg.PocketBasePassword, time.Hour),
MaxUpload: int64(cfg.MaxUploadMB) << 20,
Search: index,
Collab: hub,
Admin: admin.Handler("/admin"),
Log: log,
+28
View File
@@ -3,6 +3,7 @@ module docwell/server
go 1.26
require (
github.com/blevesearch/bleve/v2 v2.6.1
github.com/coder/websocket v1.8.15
github.com/oapi-codegen/runtime v1.8.0
github.com/tetratelabs/wazero v1.12.0
@@ -10,11 +11,36 @@ require (
)
require (
github.com/RoaringBitmap/roaring/v2 v2.14.5 // indirect
github.com/bits-and-blooms/bitset v1.24.2 // indirect
github.com/blevesearch/bleve_index_api v1.4.1 // indirect
github.com/blevesearch/geo v0.2.6 // indirect
github.com/blevesearch/go-faiss v1.1.5 // indirect
github.com/blevesearch/go-porterstemmer v1.0.3 // indirect
github.com/blevesearch/gtreap v0.1.1 // indirect
github.com/blevesearch/mmap-go v1.2.0 // indirect
github.com/blevesearch/scorch_segment_api/v2 v2.4.10 // indirect
github.com/blevesearch/segment v0.9.1 // indirect
github.com/blevesearch/snowballstem v0.9.0 // indirect
github.com/blevesearch/upsidedown_store_api v1.0.2 // indirect
github.com/blevesearch/vellum v1.2.0 // indirect
github.com/blevesearch/zapx/v11 v11.4.3 // indirect
github.com/blevesearch/zapx/v12 v12.4.3 // indirect
github.com/blevesearch/zapx/v13 v13.4.3 // indirect
github.com/blevesearch/zapx/v14 v14.4.3 // indirect
github.com/blevesearch/zapx/v15 v15.4.3 // indirect
github.com/blevesearch/zapx/v16 v16.3.4 // indirect
github.com/blevesearch/zapx/v17 v17.2.3 // indirect
github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936 // indirect
github.com/getkin/kin-openapi v0.142.0 // indirect
github.com/go-openapi/jsonpointer v0.23.1 // indirect
github.com/go-openapi/swag/jsonname v0.26.0 // indirect
github.com/golang/snappy v1.0.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/mschoch/smat v0.2.0 // indirect
github.com/oapi-codegen/oapi-codegen/v2 v2.8.1 // indirect
github.com/oasdiff/yaml v0.1.1 // indirect
github.com/oasdiff/yaml3 v0.0.14 // indirect
@@ -22,12 +48,14 @@ require (
github.com/speakeasy-api/jsonpath v0.6.3 // indirect
github.com/speakeasy-api/openapi v1.24.0 // indirect
github.com/vmware-labs/yaml-jsonpath v0.3.2 // indirect
go.etcd.io/bbolt v1.4.0 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/mod v0.38.0 // indirect
golang.org/x/sync v0.22.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/text v0.40.0 // indirect
golang.org/x/tools v0.48.0 // indirect
google.golang.org/protobuf v1.36.6 // indirect
)
tool github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen
+61 -2
View File
@@ -1,3 +1,45 @@
github.com/RoaringBitmap/roaring/v2 v2.14.5 h1:ckd0o545JqDPeVJDgeFoaM21eBixUnlWfYgjE5VnyWw=
github.com/RoaringBitmap/roaring/v2 v2.14.5/go.mod h1:eq4wdNXxtJIS/oikeCzdX1rBzek7ANzbth041hrU8Q4=
github.com/bits-and-blooms/bitset v1.24.2 h1:M7/NzVbsytmtfHbumG+K2bremQPMJuqv1JD3vOaFxp0=
github.com/bits-and-blooms/bitset v1.24.2/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8=
github.com/blevesearch/bleve/v2 v2.6.1 h1:47vLskRTqxvQEtxVPYHjf5KpOgzD2msslXFjvUQCgWQ=
github.com/blevesearch/bleve/v2 v2.6.1/go.mod h1:Dvvx6ZoEBTOj6RSzfk0lEz0wce/qhe2yOUubXeuzd2c=
github.com/blevesearch/bleve_index_api v1.4.1 h1:CYIyecFlI+/RYjzUm+NmDjYbSvk870Bb7f+Vl4b12q8=
github.com/blevesearch/bleve_index_api v1.4.1/go.mod h1:xvd48t5XMeeioWQ5/jZvgLrV98flT2rdvEJ3l/ki4Ko=
github.com/blevesearch/geo v0.2.6 h1:7K1oyQKYlauC+mJuo2AfNPyjN/4mihEoJMfyClVH1Mo=
github.com/blevesearch/geo v0.2.6/go.mod h1:6qzVUiB4BK47QkSZcRqiXEP2W3EeXuzM5XFTF8AdZ8A=
github.com/blevesearch/go-faiss v1.1.5 h1:/IU5lkOahH9Ghfk9n3F6N0XD7PYVXZJWmNDc9TtXuco=
github.com/blevesearch/go-faiss v1.1.5/go.mod h1:w3W9AiWsFRGVaMG+/cmJi7iHEAuGyC6blsgO1EzCK/M=
github.com/blevesearch/go-porterstemmer v1.0.3 h1:GtmsqID0aZdCSNiY8SkuPJ12pD4jI+DdXTAn4YRcHCo=
github.com/blevesearch/go-porterstemmer v1.0.3/go.mod h1:angGc5Ht+k2xhJdZi511LtmxuEf0OVpvUUNrwmM1P7M=
github.com/blevesearch/gtreap v0.1.1 h1:2JWigFrzDMR+42WGIN/V2p0cUvn4UP3C4Q5nmaZGW8Y=
github.com/blevesearch/gtreap v0.1.1/go.mod h1:QaQyDRAT51sotthUWAH4Sj08awFSSWzgYICSZ3w0tYk=
github.com/blevesearch/mmap-go v1.2.0 h1:l33nNKPFcBjJUMwem6sAYJPUzhUCABoK9FxZDGiFNBI=
github.com/blevesearch/mmap-go v1.2.0/go.mod h1:Vd6+20GBhEdwJnU1Xohgt88XCD/CTWcqbCNxkZpyBo0=
github.com/blevesearch/scorch_segment_api/v2 v2.4.10 h1:C3873+iWZ0YJM2ijaSHhJJzSvD4x1k+5UaQdGygZVhM=
github.com/blevesearch/scorch_segment_api/v2 v2.4.10/go.mod h1:WUUkAocbkDlNK/kgAE13NvS9oxe+u618mYZ8sOvcCc4=
github.com/blevesearch/segment v0.9.1 h1:+dThDy+Lvgj5JMxhmOVlgFfkUtZV2kw49xax4+jTfSU=
github.com/blevesearch/segment v0.9.1/go.mod h1:zN21iLm7+GnBHWTao9I+Au/7MBiL8pPFtJBJTsk6kQw=
github.com/blevesearch/snowballstem v0.9.0 h1:lMQ189YspGP6sXvZQ4WZ+MLawfV8wOmPoD/iWeNXm8s=
github.com/blevesearch/snowballstem v0.9.0/go.mod h1:PivSj3JMc8WuaFkTSRDW2SlrulNWPl4ABg1tC/hlgLs=
github.com/blevesearch/upsidedown_store_api v1.0.2 h1:U53Q6YoWEARVLd1OYNc9kvhBMGZzVrdmaozG2MfoB+A=
github.com/blevesearch/upsidedown_store_api v1.0.2/go.mod h1:M01mh3Gpfy56Ps/UXHjEO/knbqyQ1Oamg8If49gRwrQ=
github.com/blevesearch/vellum v1.2.0 h1:xkDiOEsHc2t3Cp0NsNZZ36pvc130sCzcGKOPMzXe+e0=
github.com/blevesearch/vellum v1.2.0/go.mod h1:uEcfBJz7mAOf0Kvq6qoEKQQkLODBF46SINYNkZNae4k=
github.com/blevesearch/zapx/v11 v11.4.3 h1:PTZOO5loKpHC/x/GzmPZNa9cw7GZIQxd5qRjwij9tHY=
github.com/blevesearch/zapx/v11 v11.4.3/go.mod h1:4gdeyy9oGa/lLa6D34R9daXNUvfMPZqUYjPwiLmekwc=
github.com/blevesearch/zapx/v12 v12.4.3 h1:eElXvAaAX4m04t//CGBQAtHNPA+Q6A1hHZVrN3LSFYo=
github.com/blevesearch/zapx/v12 v12.4.3/go.mod h1:TdFmr7afSz1hFh/SIBCCZvcLfzYvievIH6aEISCte58=
github.com/blevesearch/zapx/v13 v13.4.3 h1:qsdhRhaSpVnqDFlRiH9vG5+KJ+dE7KAW9WyZz/KXAiE=
github.com/blevesearch/zapx/v13 v13.4.3/go.mod h1:knK8z2NdQHlb5ot/uj8wuvOq5PhDGjNYQQy0QDnopZk=
github.com/blevesearch/zapx/v14 v14.4.3 h1:GY4Hecx0C6UTmiNC2pKdeA2rOKiLR5/rwpU9WR51dgM=
github.com/blevesearch/zapx/v14 v14.4.3/go.mod h1:rz0XNb/OZSMjNorufDGSpFpjoFKhXmppH9Hi7a877D8=
github.com/blevesearch/zapx/v15 v15.4.3 h1:iJiMJOHrz216jyO6lS0m9RTCEkprUnzvqAI2lc/0/CU=
github.com/blevesearch/zapx/v15 v15.4.3/go.mod h1:1pssev/59FsuWcgSnTa0OeEpOzmhtmr/0/11H0Z8+Nw=
github.com/blevesearch/zapx/v16 v16.3.4 h1:hDAqA8qusZTNbPEL7//w5P65UZ2de6yhSeUaTbp0Po0=
github.com/blevesearch/zapx/v16 v16.3.4/go.mod h1:zqkPPqs9GS9FzVWzCO3Wf1X044yWAV17+4zb+FTiEHg=
github.com/blevesearch/zapx/v17 v17.2.3 h1:UYYJPAt5b2tVxldx5h0jmv23RMsg8/UZKFVya7v92po=
github.com/blevesearch/zapx/v17 v17.2.3/go.mod h1:r7mb4QWbDQSkbAnOjCb9iCfkcrzajB4yBdJpuBIo/fE=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
@@ -33,17 +75,22 @@ github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvq
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs=
github.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
@@ -51,6 +98,13 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/mschoch/smat v0.2.0 h1:8imxQsjDm8yFEAVBe7azKmKSgzSkZXDuKkSq9374khM=
github.com/mschoch/smat v0.2.0/go.mod h1:kc9mz7DoBKqDyiRL7VZN8KvXQMWeTaVnttLRXOlotKw=
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
@@ -88,6 +142,7 @@ github.com/speakeasy-api/jsonpath v0.6.3/go.mod h1:2cXloNuQ+RSXi5HTRaeBh7JEmjRXT
github.com/speakeasy-api/openapi v1.24.0 h1:opoD27rupX7zBVPq1HkIGLeMOzNNA7JalhYP8q34i04=
github.com/speakeasy-api/openapi v1.24.0/go.mod h1:g3+dIMe0AYgbbGvnlQZqesmjAVWSm9BmsjLevnefQrg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
@@ -97,6 +152,8 @@ github.com/tetratelabs/wazero v1.12.0/go.mod h1:LvKtzl2RqO4gyF27BiXU+nKAjcV8f38U
github.com/vmware-labs/yaml-jsonpath v0.3.2 h1:/5QKeCBGdsInyDCyVNLbXyilb61MXGi9NP674f9Hobk=
github.com/vmware-labs/yaml-jsonpath v0.3.2/go.mod h1:U6whw1z03QyqgWdgXxvVnQ90zN1BWz5V+51Ewf8k+rQ=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
go.etcd.io/bbolt v1.4.0 h1:TU77id3TnN/zKr7CO/uk+fBCwF2jGcMuw2B/FMAzYIk=
go.etcd.io/bbolt v1.4.0/go.mod h1:AsD+OCi/qPN1giOX1aiLAha3o1U8rAz65bvN4j0sRuk=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
@@ -160,6 +217,8 @@ google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzi
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
+27
View File
@@ -479,6 +479,27 @@ type PublicSettings struct {
// Role Instance role. admin manages their own organization; superadmin manages everything.
type Role string
// SearchHit defines model for SearchHit.
type SearchHit struct {
// Highlights [start, end) character offsets of matches in snippet
Highlights [][]int `json:"highlights"`
Icon string `json:"icon"`
Id string `json:"id"`
// Snippet Plain text around the first match
Snippet string `json:"snippet"`
Space string `json:"space"`
SpaceName string `json:"spaceName"`
Title string `json:"title"`
Updated string `json:"updated"`
}
// SearchResult defines model for SearchResult.
type SearchResult struct {
Items []SearchHit `json:"items"`
Total int `json:"total"`
}
// Session defines model for Session.
type Session struct {
Token string `json:"token"`
@@ -809,6 +830,12 @@ type ListRecentPagesParams struct {
Limit *int `form:"limit,omitempty" json:"limit,omitempty"`
}
// SearchPagesParams defines parameters for SearchPages.
type SearchPagesParams struct {
Q string `form:"q" json:"q"`
Limit *int `form:"limit,omitempty" json:"limit,omitempty"`
}
// CreateSpaceJSONBody defines parameters for CreateSpace.
type CreateSpaceJSONBody struct {
Description *string `json:"description,omitempty"`
+3
View File
@@ -30,6 +30,8 @@ type Config struct {
PocketBaseEmail string
PocketBasePassword string
// DataDir holds docwell-server's own files (the search index).
DataDir string
// MaxUploadMB caps one attachment.
MaxUploadMB int
@@ -59,6 +61,7 @@ func fromLookup(lookup func(string) (string, bool)) (Config, error) {
PocketBasePassword: get("DOCWELL_PB_PASSWORD", ""),
SignupEnabled: get("DOCWELL_SIGNUP_ENABLED", "true") == "true",
SignupDomains: splitList(get("DOCWELL_SIGNUP_DOMAINS", "")),
DataDir: get("DOCWELL_DATA_DIR", "./data"),
ShutdownTimeout: 15 * time.Second,
}
+1
View File
@@ -29,6 +29,7 @@ type Service struct {
mailer Mailer
// maxUpload caps one attachment in bytes (0 = 50 MB).
maxUpload int64
search Searcher
}
func New(pb *pocketbase.Client, forget func(userID string), docs Docs) *Service {
+57
View File
@@ -0,0 +1,57 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package directory
import (
"context"
"docwell/server/internal/access"
"docwell/server/internal/search"
)
// Searcher is the part of search.Index this package uses.
type Searcher interface {
Query(ctx context.Context, workspace string, spaces []string, text string, limit int) ([]search.Hit, int, error)
}
// UseSearch enables Search.
func (s *Service) UseSearch(x Searcher) { s.search = x }
type SearchHit struct {
search.Hit
SpaceName string `json:"spaceName"`
}
type SearchResult struct {
Items []SearchHit `json:"items"`
Total int `json:"total"`
}
// Search finds pages in a workspace, only in the spaces c can open.
func (s *Service) Search(ctx context.Context, c access.Caller, wsID, text string, limit int) (SearchResult, error) {
spaces, err := s.ListSpaces(ctx, c, wsID)
if err != nil {
return SearchResult{}, err
}
out := SearchResult{Items: []SearchHit{}}
if s.search == nil || len(spaces) == 0 {
return out, nil
}
ids := make([]string, len(spaces))
names := make(map[string]string, len(spaces))
for i, sp := range spaces {
ids[i], names[sp.ID] = sp.ID, sp.Name
}
if limit <= 0 {
limit = 20
}
hits, total, err := s.search.Query(ctx, wsID, ids, text, limit)
if err != nil {
return SearchResult{}, err
}
for _, h := range hits {
out.Items = append(out.Items, SearchHit{Hit: h, SpaceName: names[h.Space]})
}
out.Total = total
return out, nil
}
+2
View File
@@ -42,6 +42,7 @@ type api struct {
dir DirectoryService
settings SettingsService
files *auth.FileTokens
index SearchIndex
collab CollabHub
log *slog.Logger
}
@@ -147,6 +148,7 @@ func (a *api) routes(mux *routeMux) {
a.inviteRoutes(mux)
a.groupRoutes(mux)
a.favoriteRoutes(mux)
a.searchRoutes(mux)
}
func (a *api) decode(w http.ResponseWriter, r *http.Request, v any) bool {
+1
View File
@@ -37,6 +37,7 @@ type DirectoryService interface {
GroupService
FavoriteService
AttachmentService
SearchService
}
func caller(r *http.Request) access.Caller {
+3 -1
View File
@@ -28,6 +28,8 @@ type Deps struct {
Settings SettingsService
// FileTokens signs the ?token= of file links; nil allows only bearer tokens.
FileTokens *auth.FileTokens
// Search is the full-text index (admin reindex); nil disables it.
Search SearchIndex
// MaxUpload caps one attachment in bytes.
MaxUpload int64
// Collab serves /collab; nil disables live editing.
@@ -58,7 +60,7 @@ func NewRouter(d Deps) http.Handler {
func newMux(d Deps) *routeMux {
mux := &routeMux{ServeMux: http.NewServeMux()}
a := &api{auth: d.Auth, dir: d.Directory, settings: d.Settings, files: d.FileTokens, collab: d.Collab, log: d.Log}
a := &api{auth: d.Auth, dir: d.Directory, settings: d.Settings, files: d.FileTokens, index: d.Search, collab: d.Collab, log: d.Log}
a.routes(mux)
a.fileRoutes(mux, max(d.MaxUpload, 1<<20))
a.collabRoute(mux, d.CORSOrigins)
+49
View File
@@ -0,0 +1,49 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package httpapi
import (
"context"
"net/http"
"strconv"
"docwell/server/internal/access"
"docwell/server/internal/directory"
)
// SearchService is the part of directory.Service that searches pages.
type SearchService interface {
Search(ctx context.Context, c access.Caller, wsID, text string, limit int) (directory.SearchResult, error)
}
// SearchIndex is the index maintenance the admin panel can trigger.
type SearchIndex interface {
Rebuild(ctx context.Context) error
Count() (uint64, error)
}
func (a *api) searchRoutes(mux *routeMux) {
mux.HandleFunc("GET /api/v1/workspaces/{id}/search", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
limit, _ := strconv.Atoi(q.Get("limit"))
res, err := a.dir.Search(r.Context(), caller(r), r.PathValue("id"), q.Get("q"), min(max(limit, 0), 50))
a.respond(w, res, err)
}))
mux.HandleFunc("POST /api/v1/admin/search/reindex", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
if err := access.ManageInstance(caller(r)); err != nil {
a.writeError(w, err)
return
}
if a.index == nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "unavailable"})
return
}
// Rebuilding can take a while; it runs on after the response.
go func() {
if err := a.index.Rebuild(context.WithoutCancel(r.Context())); err != nil {
a.log.Error("search: rebuild failed", "err", err)
}
}()
w.WriteHeader(http.StatusAccepted)
}))
}
+353
View File
@@ -0,0 +1,353 @@
// 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
}
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.CatchUp(ctx); err != nil && ctx.Err() == nil {
x.log.Warn("search: indexing failed", "err", err)
}
if time.Since(lastSweep) >= sweepEvery {
if err := 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)
}
+88
View File
@@ -0,0 +1,88 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package search
import (
"context"
"io"
"log/slog"
"testing"
)
func newIndex(t *testing.T) *Index {
t.Helper()
x, err := OpenMemory(nil, slog.New(slog.NewTextHandler(io.Discard, nil)))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = x.Close() })
return x
}
func TestQueryScopesAndRanks(t *testing.T) {
x := newIndex(t)
put := func(id, ws, space, title, text string) {
if err := x.Put(id, doc{Workspace: ws, Space: space, Title: title, Text: text}); err != nil {
t.Fatal(err)
}
}
put("p1", "w1", "s1", "Deployment guide", "How we ship the server to production.")
put("p2", "w1", "s1", "Meeting notes", "We talked about the deployment window.")
put("p3", "w1", "s2", "Deployment secrets", "Private space.")
put("p4", "w2", "s9", "Deployment elsewhere", "Another workspace.")
ctx := context.Background()
hits, total, err := x.Query(ctx, "w1", []string{"s1"}, "deployment", 10)
if err != nil {
t.Fatal(err)
}
if total != 2 || len(hits) != 2 {
t.Fatalf("hits = %+v (total %d)", hits, total)
}
if hits[0].ID != "p1" {
t.Errorf("a title match must rank first: %+v", hits)
}
for _, h := range hits {
if h.ID == "p3" || h.ID == "p4" {
t.Errorf("%s is outside the caller's spaces", h.ID)
}
}
// Typing: the last word matches as a prefix.
if hits, _, _ := x.Query(ctx, "w1", []string{"s1"}, "meet", 10); len(hits) != 1 || hits[0].ID != "p2" {
t.Errorf("prefix = %+v", hits)
}
// One wrong letter is forgiven.
if hits, _, _ := x.Query(ctx, "w1", []string{"s1"}, "deploymant", 10); len(hits) == 0 {
t.Error("fuzzy match failed")
}
if hits, _, _ := x.Query(ctx, "w1", nil, "deployment", 10); len(hits) != 0 {
t.Error("no visible spaces must find nothing")
}
if err := x.Remove("p1"); err != nil {
t.Fatal(err)
}
if hits, _, _ := x.Query(ctx, "w1", []string{"s1"}, "guide", 10); len(hits) != 0 {
t.Errorf("removed page still found: %+v", hits)
}
}
func TestSnippet(t *testing.T) {
text := "Zażółć gęślą jaźń. The quick brown fox jumps over the lazy dog."
start := len("Zażółć gęślą jaźń. The quick ")
snippet, marks := Snippet(text, [][2]int{{start, start + len("brown")}}, 30)
if len(marks) != 1 {
t.Fatalf("marks = %v (%q)", marks, snippet)
}
runes := []rune(snippet)
if got := string(runes[marks[0][0]:marks[0][1]]); got != "brown" {
t.Errorf("mark covers %q in %q", got, snippet)
}
if s, m := Snippet("", nil, 10); s != "" || len(m) != 0 {
t.Error("empty text")
}
if s, _ := Snippet("short", nil, 100); s != "short" {
t.Errorf("short = %q", s)
}
}
+64
View File
@@ -0,0 +1,64 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package search
import (
"sort"
"strings"
"unicode/utf8"
)
// Snippet cuts about width runes of text around the first match. spans are
// byte offsets [start, end) of matches in text (as Bleve reports them); the
// returned marks are rune offsets of the matches inside the snippet.
func Snippet(text string, spans [][2]int, width int) (string, [][2]int) {
marks := [][2]int{}
if text == "" {
return "", marks
}
sort.Slice(spans, func(i, j int) bool { return spans[i][0] < spans[j][0] })
// Start a little before the first match, on a word boundary.
start := 0
if len(spans) > 0 && spans[0][0] < len(text) {
start = spans[0][0]
for back := 0; start > 0 && back < width/4; back++ {
_, size := utf8.DecodeLastRuneInString(text[:start])
start -= size
}
if start > 0 {
if i := strings.IndexByte(text[start:spans[0][0]], ' '); i >= 0 {
start += i + 1
}
}
}
end := start
for n := 0; end < len(text) && n < width; n++ {
_, size := utf8.DecodeRuneInString(text[end:])
end += size
}
if end < len(text) {
if i := strings.LastIndexByte(text[start:end], ' '); i > width/2 {
end = start + i
}
}
prefix, suffix := "", ""
if start > 0 {
prefix = "…"
}
if end < len(text) {
suffix = "…"
}
snippet := prefix + text[start:end] + suffix
offset := utf8.RuneCountInString(prefix)
for _, s := range spans {
if s[0] < start || s[1] > end || s[0] >= s[1] {
continue
}
a := offset + utf8.RuneCountInString(text[start:s[0]])
b := a + utf8.RuneCountInString(text[s[0]:s[1]])
marks = append(marks, [2]int{a, b})
}
return snippet, marks
}
@@ -11,6 +11,7 @@ import { useFavoritesStore } from "../stores/favorites";
import { useSpacesStore } from "../stores/spaces";
import { atLeast, useWorkspacesStore } from "../stores/workspaces";
import PageTreeNode from "./PageTreeNode.vue";
import SearchPalette from "./SearchPalette.vue";
import ServerStatus from "./ServerStatus.vue";
import WorkspaceSwitcher from "./WorkspaceSwitcher.vue";
@@ -28,6 +29,7 @@ const errors = useFormErrors();
const sidebar = useSidebar();
const error = ref("");
const searchOpen = ref(false);
function showError(e: unknown) {
errors.show(e);
@@ -49,11 +51,14 @@ watch(
() => (sidebar.mobileOpen.value = false),
);
// Ctrl+/ (Cmd+/ on macOS) folds the sidebar, as in other editors.
// Ctrl+/ (Cmd+/ on macOS) folds the sidebar, as in other editors; Ctrl+K searches.
function onKey(e: KeyboardEvent) {
if ((e.ctrlKey || e.metaKey) && e.key === "/") {
e.preventDefault();
sidebar.toggle();
} else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "k" && !e.shiftKey && !e.altKey) {
e.preventDefault();
searchOpen.value = !searchOpen.value;
}
}
onMounted(() => document.addEventListener("keydown", onKey));
@@ -139,6 +144,7 @@ function signOut() {
<template>
<div class="flex h-dvh bg-surface-sunken" :class="{ 'cursor-col-resize select-none': resizing }">
<SearchPalette v-model="searchOpen" />
<aside
class="fixed inset-y-0 left-0 z-30 flex max-w-[85vw] flex-col bg-surface-sunken transition-transform duration-200 ease-out md:relative md:z-auto md:translate-x-0 md:transition-none"
:class="[
@@ -164,6 +170,8 @@ function signOut() {
<div class="flex items-center gap-1">
<button
class="flex h-control-sm min-w-0 flex-1 cursor-pointer items-center gap-2 rounded-sm border border-line bg-surface px-2 text-left text-ink-muted hover:border-line-strong hover:text-ink"
data-testid="search-open"
@click="searchOpen = true"
>
<DwIcon name="search" :size="16" />
<span class="flex-1 truncate">{{ $t("app.search") }}</span>
@@ -0,0 +1,179 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import type { PageItem, SearchHit } from "@docwell/api-client";
import { DwIcon } from "@docwell/ui";
import { computed, nextTick, ref, watch } from "vue";
import { useRouter } from "vue-router";
import { useApi } from "../api";
import { useWorkspacesStore } from "../stores/workspaces";
// The Ctrl+K palette: full-text search of the current workspace, showing the
// recently visited pages until something is typed.
const open = defineModel<boolean>({ default: false });
const api = useApi();
const router = useRouter();
const workspaces = useWorkspacesStore();
const input = ref<HTMLInputElement | null>(null);
const q = ref("");
const hits = ref<SearchHit[]>([]);
const recent = ref<PageItem[]>([]);
const active = ref(0);
const loading = ref(false);
const failed = ref(false);
type Row = { id: string; title: string; icon: string; spaceName: string; parts: { text: string; mark: boolean }[] };
/** Splits a snippet into plain and highlighted runs (offsets count characters, not UTF-16 units). */
function parts(snippet: string, highlights: number[][]): Row["parts"] {
const chars = [...snippet];
const out: Row["parts"] = [];
let at = 0;
for (const [a = 0, b = 0] of [...highlights].sort((x, y) => (x[0] ?? 0) - (y[0] ?? 0))) {
if (a < at || b <= a) continue;
if (a > at) out.push({ text: chars.slice(at, a).join(""), mark: false });
out.push({ text: chars.slice(a, b).join(""), mark: true });
at = b;
}
if (at < chars.length) out.push({ text: chars.slice(at).join(""), mark: false });
return out;
}
const rows = computed<Row[]>(() =>
q.value.trim()
? hits.value.map((h) => ({ ...h, parts: parts(h.snippet, h.highlights) }))
: recent.value.map((p) => ({ ...p, parts: [] })),
);
watch(open, async (v) => {
if (!v) return;
q.value = "";
hits.value = [];
active.value = 0;
await nextTick();
input.value?.focus();
const ws = workspaces.current;
if (ws) recent.value = await api.workspaces.recent(ws.id, 8).catch(() => []);
});
// Search after a short pause in typing; only the latest answer counts.
let timer: ReturnType<typeof setTimeout> | undefined;
let seq = 0;
watch(q, (text) => {
clearTimeout(timer);
active.value = 0;
failed.value = false;
const ws = workspaces.current;
if (!text.trim() || !ws) {
hits.value = [];
loading.value = false;
return;
}
loading.value = true;
timer = setTimeout(async () => {
const mine = ++seq;
try {
const res = await api.workspaces.search(ws.id, text, 20);
if (mine === seq) hits.value = res.items;
} catch {
if (mine === seq) failed.value = true;
} finally {
if (mine === seq) loading.value = false;
}
}, 150);
});
function go(row: Row | undefined) {
if (!row) return;
open.value = false;
router.push({ name: "page", params: { id: row.id } });
}
function onKey(e: KeyboardEvent) {
const n = rows.value.length;
if (e.key === "ArrowDown" && n) {
e.preventDefault();
active.value = (active.value + 1) % n;
} else if (e.key === "ArrowUp" && n) {
e.preventDefault();
active.value = (active.value - 1 + n) % n;
} else if (e.key === "Enter") {
e.preventDefault();
go(rows.value[active.value]);
} else if (e.key === "Escape") {
e.preventDefault();
open.value = false;
}
}
</script>
<template>
<Teleport to="body">
<div
v-if="open"
class="fixed inset-0 z-50 flex items-start justify-center bg-black/40 px-4 pt-[12vh]"
data-testid="search-palette"
@mousedown.self="open = false"
>
<div
class="w-full max-w-xl overflow-hidden rounded-md border border-line bg-surface-raised shadow-dialog"
role="dialog"
aria-modal="true"
:aria-label="$t('app.search')"
>
<div class="flex items-center gap-2 border-b border-line px-3">
<DwIcon name="search" :size="18" class="text-ink-muted" />
<input
ref="input"
v-model="q"
type="search"
maxlength="200"
class="h-12 min-w-0 flex-1 bg-transparent text-ui-lg text-ink outline-none placeholder:text-ink-faint"
:placeholder="$t('search.placeholder')"
:aria-label="$t('app.search')"
role="combobox"
aria-controls="search-results"
:aria-expanded="rows.length > 0"
:aria-activedescendant="rows.length ? `search-row-${active}` : undefined"
@keydown="onKey"
/>
<kbd class="font-mono text-[11px] text-ink-faint">Esc</kbd>
</div>
<p v-if="!q.trim() && rows.length" class="px-4 pt-3 dw-label">{{ $t("home.recent") }}</p>
<ul id="search-results" role="listbox" class="max-h-[50vh] overflow-y-auto p-1">
<li
v-for="(r, i) in rows"
:id="`search-row-${i}`"
:key="r.id"
role="option"
:aria-selected="i === active"
class="flex cursor-pointer gap-3 rounded-sm px-3 py-2"
:class="{ 'bg-surface-hover': i === active }"
data-testid="search-result"
@mousemove="active = i"
@mousedown.prevent="go(r)"
>
<span v-if="r.icon" class="w-5 shrink-0 text-center">{{ r.icon }}</span>
<DwIcon v-else name="page" :size="18" class="mt-0.5 text-ink-muted" />
<span class="min-w-0 flex-1">
<span class="flex items-baseline gap-2">
<span class="truncate text-ui-md font-medium text-ink">{{ r.title || $t("home.untitled") }}</span>
<span class="shrink-0 text-ui-xs text-ink-muted">{{ r.spaceName }}</span>
</span>
<span v-if="r.parts.length" class="mt-0.5 line-clamp-2 block text-ui-sm text-ink-muted">
<template v-for="(p, j) in r.parts" :key="j">
<mark v-if="p.mark" class="rounded-xs bg-accent-soft text-ink">{{ p.text }}</mark>
<template v-else>{{ p.text }}</template>
</template>
</span>
</span>
</li>
</ul>
<p v-if="q.trim() && !loading && !rows.length" class="px-4 pt-1 pb-4 text-ui-md text-ink-muted">
{{ failed ? $t("errors.unknown") : $t("search.none", { q }) }}
</p>
</div>
</div>
</Teleport>
</template>
+4
View File
@@ -270,5 +270,9 @@
"none": "No groups yet.",
"pick": "Choose a group",
"noneToAdd": "This workspace has no groups yet. Create them in the workspace settings."
},
"search": {
"placeholder": "Search pages…",
"none": "Nothing found for \"{q}\"."
}
}
+4
View File
@@ -270,5 +270,9 @@
"none": "Brak grup.",
"pick": "Wybierz grupę",
"noneToAdd": "Ten obszar roboczy nie ma jeszcze grup. Utwórz je w ustawieniach obszaru roboczego."
},
"search": {
"placeholder": "Szukaj stron…",
"none": "Nic nie znaleziono dla „{q}”."
}
}
+50
View File
@@ -1362,6 +1362,35 @@ paths:
schema: { type: string, format: binary }
"401": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/workspaces/{id}/search:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
get:
operationId: searchPages
tags: [search]
summary: Full-text search of page titles and text, in the spaces the caller can open
description: >-
Trashed pages are not found. The index catches up with edits within a few seconds.
security: [{ bearer: [] }]
parameters:
- { name: q, in: query, required: true, schema: { type: string, maxLength: 200 } }
- { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 50 } }
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/SearchResult" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/admin/search/reindex:
post:
operationId: reindexSearch
tags: [search]
summary: Rebuild the search index from the database (superadmin)
security: [{ bearer: [] }]
responses:
"202": { description: Started }
"403": { $ref: "#/components/responses/Error" }
components:
securitySchemes:
bearer:
@@ -1783,3 +1812,24 @@ components:
size: { type: integer, description: Bytes }
url: { type: string, description: "API path, e.g. /api/v1/files/abc" }
created: { type: string }
SearchHit:
type: object
required: [id, title, icon, space, spaceName, snippet, highlights, updated]
properties:
id: { type: string }
title: { type: string }
icon: { type: string }
space: { type: string }
spaceName: { type: string }
snippet: { type: string, description: Plain text around the first match }
highlights:
type: array
description: "[start, end) character offsets of matches in snippet"
items: { type: array, items: { type: integer }, minItems: 2, maxItems: 2 }
updated: { type: string }
SearchResult:
type: object
required: [items, total]
properties:
items: { type: array, items: { $ref: "#/components/schemas/SearchHit" } }
total: { type: integer }