Files
pages/internal/server/search_suggest.go
T
Anya Tokugawa d5d21b7841
Build and publish container images / images (push) Successful in 9m34s
Release container images / release (push) Successful in 36s
Refactor architecture into eight components and consolidate reliability work
Extract Grammaratur, Dregarnuhr, Geduldh, Mestionora, Ordoschnellic, Schutzaria, Kunstzeal and Seheweit behind compatible application contracts.

Include accumulated editor resilience, navigation and theme UX, remote CLI, storage/schema and DR groundwork, tests and design/operations documentation.

Verified: uncached full Go suite; go vet ./...; race tests for all eight components; 11 targeted Chromium tests; Node suites; 19 Python CLI tests; reproducible editor build. No push, release tag or deployment in this checkpoint.
2026-11-01 15:23:31 +09:00

139 lines
4.2 KiB
Go

package server
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/url"
"path"
"sort"
"strings"
"time"
"unicode/utf8"
"pageswiki/internal/store"
)
type searchSuggestionItem struct {
Kind string `json:"kind"`
Label string `json:"label"`
Path string `json:"path"`
Href string `json:"href"`
Context string `json:"context,omitempty"`
ContentType string `json:"content_type,omitempty"`
Match string `json:"match,omitempty"`
Exact bool `json:"exact,omitempty"`
}
func suggestionExact(query string, values ...string) bool {
query = strings.TrimPrefix(strings.ToLower(strings.TrimSpace(query)), "/")
for _, value := range values {
if strings.TrimPrefix(strings.ToLower(strings.TrimSpace(value)), "/") == query {
return true
}
}
return false
}
func pageSuggestion(result store.PathSuggestion, query string) searchSuggestionItem {
name := path.Base(result.Path)
if result.Filename != "" {
name = path.Base(result.Filename)
}
if result.Title != "" {
name = result.Title
}
kind := "file"
if strings.HasPrefix(strings.ToLower(result.ContentType), "text/html") {
kind = "page"
}
match := "body"
if result.PathMatch {
match = "path"
} else if result.FilenameMatch {
match = "filename"
}
return searchSuggestionItem{
Kind: kind, Label: name, Path: result.Path,
Href: (&url.URL{Path: result.Path}).EscapedPath(),
ContentType: result.ContentType, Match: match,
Exact: suggestionExact(query, result.Path, path.Base(result.Path), result.Filename, result.Title),
}
}
func citySuggestion(result store.CitySearchResult, query string) searchSuggestionItem {
label := result.DisplayTitle()
parents := make([]string, 0, 2)
if result.QuartierTitle != "" {
parents = append(parents, result.QuartierTitle)
}
if result.StreetTitle != "" {
parents = append(parents, result.StreetTitle)
}
match := "description"
if result.NameMatch {
match = "name"
} else if result.PathMatch {
match = "path"
}
return searchSuggestionItem{
Kind: result.Kind, Label: label, Path: result.ContentPath(),
Href: cityContentHref(result),
Context: strings.Join(parents, " / "), Match: match,
Exact: suggestionExact(query, result.Name, label, result.ContentPath()),
}
}
func (s *Server) handleSearchSuggestAPI(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.Header().Set("Allow", http.MethodGet)
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Cache-Control", "private, no-store")
query := strings.TrimSpace(r.URL.Query().Get("q"))
if len(query) > 256 || len(strings.Fields(query)) > 8 {
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(map[string]string{"error": "query too long"})
return
}
if utf8.RuneCountInString(query) < 2 {
_ = json.NewEncoder(w).Encode(map[string]any{"items": []searchSuggestionItem{}})
return
}
ctx, cancel := context.WithTimeout(r.Context(), 700*time.Millisecond)
defer cancel()
domain := s.domainUUIDForRequest(r)
allowed := s.pathReadFilter(r)
pages, err := s.searchEngine().SearchPathSuggestionsInDomain(ctx, domain, "/", query, 8, allowed)
if err != nil {
status := http.StatusInternalServerError
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
status = http.StatusServiceUnavailable
}
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(map[string]string{"error": "suggestions unavailable"})
return
}
items := make([]searchSuggestionItem, 0, 12)
// City metadata is useful but optional enrichment. A slow City query must
// not discard already-authorized Page suggestions.
if city, cityErr := s.searchEngine().SearchCityInDomain(ctx, domain, "/", query, 4, allowed, store.SearchOptions{}); cityErr == nil {
for _, result := range city {
items = append(items, citySuggestion(result, query))
}
}
for _, result := range pages {
items = append(items, pageSuggestion(result, query))
}
sort.SliceStable(items, func(i, j int) bool {
if items[i].Exact != items[j].Exact {
return items[i].Exact
}
return false
})
_ = json.NewEncoder(w).Encode(map[string]any{"items": items})
}