forked from google/zoekt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream.go
165 lines (137 loc) · 3.71 KB
/
stream.go
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
// Package stream provides a client and a server to consume search results as
// stream.
package stream
import (
"encoding/gob"
"errors"
"net/http"
"sync"
"github.com/henrik242/zoekt"
"github.com/henrik242/zoekt/query"
"github.com/henrik242/zoekt/rpc"
)
// DefaultSSEPath is the path used by zoekt-webserver.
const DefaultSSEPath = "/stream"
type eventType int
const (
eventMatches eventType = iota
eventError
eventDone
)
func (e eventType) string() string {
return []string{"eventMatches", "eventError", "eventDone"}[e]
}
// Server returns an http.Handler which is the server side of StreamSearch.
func Server(searcher zoekt.Streamer) http.Handler {
registerGob()
return &handler{Searcher: searcher}
}
type searchArgs struct {
Q query.Q
Opts *zoekt.SearchOptions
}
type searchReply struct {
Event eventType
Data interface{}
}
type handler struct {
Searcher zoekt.Streamer
}
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
// Decode payload.
args := new(searchArgs)
err := gob.NewDecoder(r.Body).Decode(args)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
args.Q = query.RPCUnwrap(args.Q)
eventWriter, err := newEventStreamWriter(w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Always send a done event in the end.
defer func() {
err = eventWriter.event(eventDone, nil)
if err != nil {
_ = eventWriter.event(eventError, err)
}
}()
aggStats := zoekt.Stats{}
send := func(zsr *zoekt.SearchResult) {
err := eventWriter.event(eventMatches, zsr)
if err != nil {
_ = eventWriter.event(eventError, err)
return
}
}
err = h.Searcher.StreamSearch(ctx, args.Q, args.Opts, SenderFunc(func(event *zoekt.SearchResult) {
// We don't want to send events over the wire if they just contain stats and no
// file matches. Hence, in case we didn't find any results, we will just
// aggregate the stats.
if len(event.Files) == 0 {
aggStats.Add(event.Stats)
return
}
// If we have aggregate stats, we merge them with the new event before sending
// it, and reset aggStats afterwards.
if !aggStats.Zero() {
defer func() { aggStats = zoekt.Stats{} }() // reset stats
event.Stats.Add(aggStats)
}
send(event)
}))
if err == nil && !aggStats.Zero() {
send(&zoekt.SearchResult{Stats: aggStats})
}
if err != nil {
_ = eventWriter.event(eventError, err)
return
}
}
type eventStreamWriter struct {
enc *gob.Encoder
flush func()
}
func newEventStreamWriter(w http.ResponseWriter) (*eventStreamWriter, error) {
flusher, ok := w.(http.Flusher)
if !ok {
return nil, errors.New("http flushing not supported")
}
w.Header().Set("Content-Type", "application/x-gob-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Transfer-Encoding", "chunked")
// This informs nginx to not buffer. With buffering search responses will
// be delayed until buffers get full, leading to worst case latency of the
// full time a search takes to complete.
w.Header().Set("X-Accel-Buffering", "no")
return &eventStreamWriter{
enc: gob.NewEncoder(w),
flush: flusher.Flush,
}, nil
}
func (e *eventStreamWriter) event(event eventType, data interface{}) error {
// Because gob does not support serializing errors, we send error.Error() and
// recreate the error on the client-side.
if event == eventError {
if err, isError := data.(error); isError {
data = err.Error()
}
}
err := e.enc.Encode(searchReply{Event: event, Data: data})
if err != nil {
return err
}
e.flush()
return nil
}
var once sync.Once
func registerGob() {
once.Do(func() {
gob.Register(&zoekt.SearchResult{})
})
rpc.RegisterGob()
}