-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_search_server.go
More file actions
147 lines (128 loc) · 3.66 KB
/
Copy pathmemory_search_server.go
File metadata and controls
147 lines (128 loc) · 3.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
package contexting
import (
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"os"
"strings"
"time"
)
// Server-side timeouts
const defaultReadHeaderTimeout = 3 * time.Second // Timeout for reading HTTP request headers (prevents slowloris)
const defaultShutdownTimeout = 2 * time.Second // Timeout for graceful HTTP server shutdown
const defaultSearchLogQueryMax = 120
type memorySearchServer struct {
runtimeFile string
listener net.Listener
httpServer *http.Server
}
type MemorySearchLogOptions struct {
Enabled bool
QueryMax int
}
type memorySearchRequest struct {
Query string `json:"query"`
Opts SearchOptions `json:"opts"`
}
type memorySearchResponse struct {
Results []SearchResult `json:"results"`
GeneratedAt time.Time `json:"generated_at"`
}
func startMemorySearchServer(ctx context.Context, manager *IndexManager, runtimeFile string, logOpts MemorySearchLogOptions) (*memorySearchServer, error) {
if logOpts.QueryMax <= 0 {
logOpts.QueryMax = defaultSearchLogQueryMax
}
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return nil, fmt.Errorf("listen memory server: %w", err)
}
mux := http.NewServeMux()
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
_, _ = w.Write([]byte("ok"))
})
mux.HandleFunc("/search", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
defer r.Body.Close()
start := time.Now()
var req memorySearchRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if logOpts.Enabled {
LogWarnf("Search request rejected: invalid payload")
}
http.Error(w, "invalid request", http.StatusBadRequest)
return
}
results := manager.Search(req.Query, req.Opts)
if logOpts.Enabled {
LogInfof("Search query \"%s\" -> %d results in %dms", formatSearchLogQuery(req.Query, logOpts.QueryMax), len(results), time.Since(start).Milliseconds())
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(memorySearchResponse{Results: results, GeneratedAt: manager.IndexGeneratedAt()})
})
httpServer := &http.Server{
Handler: mux,
ReadHeaderTimeout: defaultReadHeaderTimeout,
}
server := &memorySearchServer{
runtimeFile: runtimeFile,
listener: listener,
httpServer: httpServer,
}
runtime := RuntimeState{
RootPath: manager.RootPath(),
Address: listener.Addr().String(),
PID: os.Getpid(),
StartedAt: time.Now().UTC(),
}
if err := SaveRuntimeState(runtimeFile, runtime); err != nil {
_ = listener.Close()
return nil, err
}
go func() {
<-ctx.Done()
_ = server.Close()
}()
go func() {
if err := httpServer.Serve(listener); err != nil && err != http.ErrServerClosed {
LogErrorf("Memory search server failed: %v", err)
}
}()
return server, nil
}
func formatSearchLogQuery(query string, max int) string {
if max <= 0 {
max = defaultSearchLogQueryMax
}
normalized := strings.Join(strings.Fields(strings.TrimSpace(query)), " ")
runes := []rune(normalized)
if len(runes) <= max {
return normalized
}
return string(runes[:max]) + "..."
}
func (s *memorySearchServer) Address() string {
if s == nil || s.listener == nil {
return ""
}
return s.listener.Addr().String()
}
func (s *memorySearchServer) Close() error {
if s == nil {
return nil
}
ctx, cancel := context.WithTimeout(context.Background(), defaultShutdownTimeout)
defer cancel()
_ = s.httpServer.Shutdown(ctx)
_ = s.listener.Close()
_ = os.Remove(s.runtimeFile)
return nil
}