-
Notifications
You must be signed in to change notification settings - Fork 104
/
searchprovider_ps.go
458 lines (393 loc) · 13.3 KB
/
searchprovider_ps.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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
package gocb
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"sync/atomic"
"time"
cbsearch "github.com/couchbase/gocb/v2/search"
"github.com/couchbase/goprotostellar/genproto/search_v1"
)
type searchProviderPs struct {
provider search_v1.SearchServiceClient
managerProvider *psOpManagerProvider
}
var _ searchProvider = &searchProviderPs{}
func (search *searchProviderPs) Search(scope *Scope, indexName string, request SearchRequest, opts *SearchOptions) (*SearchResult, error) {
return nil, ErrFeatureNotAvailable
}
// SearchQuery executes a search query against PS, taking care of the translation.
func (search *searchProviderPs) SearchQuery(indexName string, query cbsearch.Query, opts *SearchOptions) (*SearchResult, error) {
if opts.ConsistentWith != nil {
return nil, wrapError(ErrFeatureNotAvailable, "the ConsistentWith search option is not supported by the couchbase2 protocol")
}
if len(opts.Raw) > 0 {
return nil, wrapError(ErrFeatureNotAvailable, "the Raw search option is not supported by the couchbase2 protocol")
}
manager := search.managerProvider.NewManager(opts.ParentSpan, "search", map[string]interface{}{
"db.operation": indexName,
})
defer manager.Finish(false)
manager.SetIsIdempotent(true)
manager.SetRetryStrategy(opts.RetryStrategy)
manager.SetTimeout(opts.Timeout)
psQuery, err := cbsearch.Internal{}.MapQueryToPs(query)
if err != nil {
return nil, err
}
psSort, err := cbsearch.Internal{}.MapSortToPs(opts.Sort)
if err != nil {
return nil, err
}
facets, err := cbsearch.Internal{}.MapFacetsToPs(opts.Facets)
if err != nil {
return nil, err
}
request := search_v1.SearchQueryRequest{
IndexName: indexName,
Query: psQuery,
Sort: psSort,
Facets: facets,
}
if opts != nil {
request.DisableScoring = opts.DisableScoring
request.Collections = opts.Collections
request.IncludeLocations = opts.IncludeLocations
request.Limit = opts.Limit
request.Skip = opts.Skip
request.IncludeExplanation = opts.Explain
request.Fields = opts.Fields
}
if opts.ScanConsistency > 0 {
switch opts.ScanConsistency { // only supports not bounded, not unset
case SearchScanConsistencyNotBounded:
request.ScanConsistency = search_v1.SearchQueryRequest_SCAN_CONSISTENCY_NOT_BOUNDED
default:
err = makeInvalidArgumentsError("invalid scan consistency option specified")
return nil, err
}
}
if opts.Highlight != nil {
request.HighlightFields = opts.Highlight.Fields
switch opts.Highlight.Style {
case DefaultHighlightStyle:
request.HighlightStyle = search_v1.SearchQueryRequest_HIGHLIGHT_STYLE_DEFAULT
case AnsiHightlightStyle:
request.HighlightStyle = search_v1.SearchQueryRequest_HIGHLIGHT_STYLE_ANSI
case HTMLHighlightStyle:
request.HighlightStyle = search_v1.SearchQueryRequest_HIGHLIGHT_STYLE_HTML
default:
err = makeInvalidArgumentsError("invalid highlight option specified")
return nil, err
}
}
userCtx := opts.Context
if userCtx == nil {
userCtx = context.Background()
}
// We create a context with a timeout which will control timing out the initial request portion
// of the operation. We can defer the cancel for this as we aren't applying this context directly
// to the request so cancellation will not terminate any streams.
timeoutCtx, timeoutCancel := context.WithTimeout(context.Background(), manager.Timeout())
defer timeoutCancel()
var cancellationIsTimeout uint32
// This second context has no real parent and will be cancelled if the user context is cancelled or the timeout
// is reached. However, if the user context does not get cancelled during the initial request portion of the
// operation then this context will live for the lifetime of the op and be used for cancelled if the user calls
// Close on the result.
doneCh := make(chan struct{})
reqCtx, reqCancel := context.WithCancel(context.Background())
go func() {
select {
case <-userCtx.Done():
if errors.Is(userCtx.Err(), context.DeadlineExceeded) {
atomic.StoreUint32(&cancellationIsTimeout, 1)
}
reqCancel()
case <-timeoutCtx.Done():
atomic.StoreUint32(&cancellationIsTimeout, 1)
reqCancel()
case <-doneCh:
}
}()
var firstRows *search_v1.SearchQueryResponse
client, err := wrapPSOpCtxWithPeek(reqCtx, manager, &request, search.provider.SearchQuery, func(client search_v1.SearchService_SearchQueryClient) error {
var err error
firstRows, err = client.Recv()
if err != nil {
return err
}
return nil
})
close(doneCh)
if err != nil {
reqCancel()
return nil, search.makeError(err, query, atomic.LoadUint32(&cancellationIsTimeout) == 1, manager.ElapsedTime(), manager.RetryInfo())
}
return newSearchResult(&psSearchRowReader{
client: client,
cancelFunc: reqCancel,
query: query,
nextRows: firstRows.GetHits(),
nextRowsIndex: 0,
meta: firstRows.MetaData,
facets: firstRows.Facets,
}), nil
}
func (search *searchProviderPs) makeError(err error, query interface{}, hasTimedOut bool, elapsed time.Duration,
retryInfo retriedRequestInfo) error {
var gocbErr *GenericError
if !errors.As(err, &gocbErr) {
return err
}
if errors.Is(err, ErrRequestCanceled) && hasTimedOut {
return &TimeoutError{
InnerError: ErrUnambiguousTimeout,
TimeObserved: elapsed,
OperationID: retryInfo.Operation(),
Opaque: retryInfo.Identifier(),
RetryReasons: retryInfo.RetryReasons(),
RetryAttempts: retryInfo.RetryAttempts(),
}
}
if gocbErr.Context == nil {
gocbErr.Context = make(map[string]interface{})
}
gocbErr.Context["query"] = query
return gocbErr
}
// wrapper around the PS result to make it compatible with
// the searchRowReader interface.
type psSearchRowReader struct {
client search_v1.SearchService_SearchQueryClient
nextRowsIndex int
nextRows []*search_v1.SearchQueryResponse_SearchQueryRow
err error
meta *search_v1.SearchQueryResponse_MetaData
cancelFunc context.CancelFunc
facets map[string]*search_v1.SearchQueryResponse_FacetResult
query cbsearch.Query
}
// returns the next search row, either from local or fetches it from the client.
func (reader *psSearchRowReader) NextRow() []byte {
// we have results so lets use them.
if reader.nextRowsIndex < len(reader.nextRows) {
row := reader.nextRows[reader.nextRowsIndex]
reader.nextRowsIndex++
convertedRow, err := psSearchRowToJSONBytes(row)
if err != nil {
reader.finishWithError(err)
return nil
}
return convertedRow
}
// check if there are anymore available results.
res, err := reader.client.Recv()
if err != nil {
if errors.Is(err, io.EOF) {
reader.finishWithoutError()
return nil
}
reader.finishWithError(err)
return nil
}
reader.nextRows = res.GetHits()
reader.nextRowsIndex = 1
reader.meta = res.MetaData
reader.facets = res.Facets
if len(res.Hits) > 0 {
convertedRow, err := psSearchRowToJSONBytes(res.Hits[0])
if errors.Is(err, io.EOF) {
reader.finishWithoutError()
return nil
}
return convertedRow
}
return nil
}
func (reader *psSearchRowReader) Close() error {
if reader.err != nil {
return reader.err
}
// if the client is nil then we must be closed already.
if reader.client == nil {
return nil
}
err := reader.client.CloseSend()
reader.client = nil
return err
}
func (reader *psSearchRowReader) MetaData() ([]byte, error) {
if reader.err != nil {
return nil, reader.Err()
}
if reader.client != nil {
return nil, errors.New("the result must be fully read before accessing the meta-data")
}
if reader.meta == nil {
return nil, errors.New("an error occurred during querying which has made the meta-data unavailable")
}
facets, err := psSearchFacetToJSONSearchFacet(reader.facets)
if err != nil {
return nil, err
}
meta := jsonSearchResponse{
TotalHits: reader.meta.Metrics.TotalRows,
MaxScore: reader.meta.Metrics.MaxScore,
Took: uint64(reader.meta.Metrics.ExecutionTime.GetNanos()), // this is in nano seconds
Status: jsonSearchResponseStatus{
Errors: reader.meta.Errors,
},
Facets: facets,
}
return json.Marshal(meta)
}
func (reader *psSearchRowReader) Err() error {
err := reader.err
if err == nil {
return nil
}
return mapPsErrorToGocbError(err, true)
}
func (reader *psSearchRowReader) finishWithoutError() {
reader.cancelFunc()
// Close the stream now that we are done with it
err := reader.client.CloseSend()
if err != nil {
logWarnf("query stream close failed after meta-data: %s", err)
}
reader.client = nil
}
func (reader *psSearchRowReader) finishWithError(err error) {
reader.cancelFunc()
// Lets record the error that happened
reader.err = err
// Lets close the underlying stream
closeErr := reader.client.CloseSend()
if closeErr != nil {
// We log this at debug level, but its almost always going to be an
// error since thats the most likely reason we are in finishWithError
logDebugf("query stream close failed after error: %s", closeErr)
}
// Our client is invalidated as soon as an error occurs
reader.client = nil
}
// Helper functions to convert from PS world into something gocb can process
func psSearchRowLocationToJSONSearchRowLocations(locations []*search_v1.SearchQueryResponse_Location) jsonSearchRowLocations {
jsonForm := make(jsonSearchRowLocations)
for _, location := range locations {
field := location.GetField()
term := location.GetTerm()
if _, ok := jsonForm[field]; !ok {
jsonForm[field] = make(map[string][]jsonRowLocation)
}
jsonForm[field][term] = append(jsonForm[field][term], jsonRowLocation{
Field: field,
Term: term,
Position: location.GetPosition(),
Start: location.GetStart(),
End: location.GetEnd(),
ArrayPositions: location.GetArrayPositions(),
})
}
return jsonForm
}
func psSearchRowFragmentToMap(fragmentMap map[string]*search_v1.SearchQueryResponse_Fragment) map[string][]string {
var result = make(map[string][]string)
for key, fragment := range fragmentMap {
result[key] = fragment.GetContent()
}
return result
}
// helper util to convert PS's SearchQueryRow to jsonSearchRow.
func psSearchRowToJSONSearchRow(row *search_v1.SearchQueryResponse_SearchQueryRow) (jsonSearchRow, error) {
fieldRaw, err := json.Marshal(row.Fields)
if err != nil {
return jsonSearchRow{}, err
}
return jsonSearchRow{
ID: row.Id,
Index: row.Index,
Score: row.Score,
Explanation: row.Explanation,
Locations: psSearchRowLocationToJSONSearchRowLocations(row.Locations),
Fragments: psSearchRowFragmentToMap(row.Fragments),
Fields: fieldRaw,
}, nil
}
// converts from ps search results to jsonRowMessage as bytes for compatibility with existing gocb code.
func psSearchRowToJSONBytes(row *search_v1.SearchQueryResponse_SearchQueryRow) ([]byte, error) {
convertedRow, err := psSearchRowToJSONSearchRow(row)
if err != nil {
return nil, err
}
rowBytes, err := json.Marshal(convertedRow)
if err != nil {
return nil, err
}
return rowBytes, nil
}
func psSearchFacetToJSONSearchFacet(facets map[string]*search_v1.SearchQueryResponse_FacetResult) (map[string]jsonSearchFacet, error) {
out := make(map[string]jsonSearchFacet)
for key, facet := range facets {
switch f := facet.SearchFacet.(type) {
case *search_v1.SearchQueryResponse_FacetResult_TermFacet:
terms := make([]jsonSearchTermFacet, len(f.TermFacet.Terms))
for index, psTerm := range f.TermFacet.Terms {
terms[index] = jsonSearchTermFacet{
Term: psTerm.Name,
Count: int(psTerm.Size), // TODO: safely convert this.
}
}
out[key] = jsonSearchFacet{
Name: key,
Field: f.TermFacet.Field,
Total: uint64(f.TermFacet.Total), // we can't have negative results and we're casting into a larger space
Missing: uint64(f.TermFacet.Missing),
Other: uint64(f.TermFacet.Other),
Terms: terms,
}
case *search_v1.SearchQueryResponse_FacetResult_DateRangeFacet:
ranges := make([]jsonSearchDateFacet, len(f.DateRangeFacet.DateRanges))
for index, psRange := range f.DateRangeFacet.DateRanges {
ranges[index] = jsonSearchDateFacet{
Name: psRange.Name,
Start: psRange.Start.AsTime().Format(time.RFC3339),
End: psRange.End.AsTime().Format(time.RFC3339),
Count: int(psRange.Size),
}
}
out[key] = jsonSearchFacet{
Name: key,
Field: f.DateRangeFacet.Field,
Total: uint64(f.DateRangeFacet.Total), // we can't have negative results and we're casting into a larger space
Missing: uint64(f.DateRangeFacet.Missing),
Other: uint64(f.DateRangeFacet.Other),
DateRanges: ranges,
}
case *search_v1.SearchQueryResponse_FacetResult_NumericRangeFacet:
ranges := make([]jsonSearchNumericFacet, len(f.NumericRangeFacet.NumericRanges))
for index, psRange := range f.NumericRangeFacet.NumericRanges {
ranges[index] = jsonSearchNumericFacet{
Name: psRange.Name,
Min: float64(psRange.Min),
Max: float64(psRange.Max),
Count: int(psRange.Size),
}
}
out[key] = jsonSearchFacet{
Name: key,
Field: f.NumericRangeFacet.Field,
Total: uint64(f.NumericRangeFacet.Total), // we can't have negative results and we're casting into a larger space
Missing: uint64(f.NumericRangeFacet.Missing),
Other: uint64(f.NumericRangeFacet.Other),
NumericRanges: ranges,
}
default:
return nil, makeInvalidArgumentsError(fmt.Sprintf("invalid search facet return: %s", key))
}
}
return out, nil
}