/
session.go
507 lines (474 loc) · 14.3 KB
/
session.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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
package search
import (
"context"
"fmt"
"regexp"
"sort"
"sync"
mapset "github.com/deckarep/golang-set"
"github.com/keybase/client/go/chat/types"
"github.com/keybase/client/go/chat/utils"
"github.com/keybase/client/go/protocol/chat1"
"github.com/keybase/client/go/protocol/gregor1"
)
// searchSession encapsulates a single search session into a three stage
// pipeline; presearch, search and postSearch.
type searchSession struct {
sync.Mutex
query, origQuery string
uid gregor1.UID
hitUICh chan chat1.ChatSearchInboxHit
indexer *Indexer
opts chat1.SearchOpts
tokens tokenMap
queryRe *regexp.Regexp
numConvsSearched int
inboxIndexStatus *inboxIndexStatus
// convID -> hit
convMap map[chat1.ConvIDStr]types.RemoteConversation
reindexConvs []chat1.ConversationID
hitMap map[chat1.ConvIDStr]chat1.ChatSearchInboxHit
convList []types.RemoteConversation
}
func newSearchSession(query, origQuery string, uid gregor1.UID,
hitUICh chan chat1.ChatSearchInboxHit, indexUICh chan chat1.ChatSearchIndexStatus,
indexer *Indexer, opts chat1.SearchOpts) *searchSession {
if opts.MaxHits > MaxAllowedSearchHits || opts.MaxHits < 0 {
opts.MaxHits = MaxAllowedSearchHits
}
if opts.BeforeContext > MaxContext || opts.BeforeContext < 0 {
opts.BeforeContext = MaxContext
}
if opts.AfterContext > MaxContext || opts.AfterContext < 0 {
opts.AfterContext = MaxContext
}
return &searchSession{
query: query,
origQuery: origQuery,
uid: uid,
hitUICh: hitUICh,
indexer: indexer,
opts: opts,
inboxIndexStatus: newInboxIndexStatus(indexUICh),
hitMap: make(map[chat1.ConvIDStr]chat1.ChatSearchInboxHit),
}
}
func (s *searchSession) getConv(convID chat1.ConversationID) types.RemoteConversation {
s.Lock()
defer s.Unlock()
return s.convMap[convID.ConvIDStr()]
}
func (s *searchSession) setHit(convID chat1.ConversationID, convHit chat1.ChatSearchInboxHit) {
s.Lock()
defer s.Unlock()
s.hitMap[convID.ConvIDStr()] = convHit
}
func (s *searchSession) incrementNumConvsSearched() {
s.Lock()
defer s.Unlock()
s.numConvsSearched++
}
// searchConv finds all messages that match the given set of tokens and opts,
// results are ordered desc by msg id.
func (s *searchSession) searchConv(ctx context.Context, convID chat1.ConversationID) (msgIDs []chat1.MessageID, err error) {
defer s.indexer.Trace(ctx, &err, fmt.Sprintf("searchConv convID: %s", convID))()
var allMsgIDs mapset.Set
for token := range s.tokens {
matchedIDs := mapset.NewThreadUnsafeSet()
idMap, err := s.indexer.store.GetHits(ctx, convID, token)
if err != nil {
return nil, err
}
for msgID := range idMap {
matchedIDs.Add(msgID)
}
if allMsgIDs == nil {
allMsgIDs = matchedIDs
} else {
allMsgIDs = allMsgIDs.Intersect(matchedIDs)
if allMsgIDs.Cardinality() == 0 {
// no matches in this conversation..
return nil, nil
}
}
}
msgIDSlice := msgIDsFromSet(allMsgIDs)
// Sort so we can truncate if necessary, returning the newest results first.
sort.Sort(utils.ByMsgID(msgIDSlice))
return msgIDSlice, nil
}
func (s *searchSession) getMsgsAndIDSet(ctx context.Context, convID chat1.ConversationID,
msgIDs []chat1.MessageID) (mapset.Set, []chat1.MessageUnboxed, error) {
idSet := mapset.NewThreadUnsafeSet()
idSetWithContext := mapset.NewThreadUnsafeSet()
// Best effort attempt to get surrounding context. We filter out
// non-visible messages so exact counts may be slightly off. We add a
// padding of MaxContext to minimize the chance of this but don't have any
// error correction in place.
for _, msgID := range msgIDs {
if s.opts.BeforeContext > 0 {
for i := 0; i < s.opts.BeforeContext+MaxContext; i++ {
// ensure we don't underflow MessageID which is a uint.
if chat1.MessageID(i+1) >= msgID {
break
}
beforeID := msgID - chat1.MessageID(i+1)
idSetWithContext.Add(beforeID)
}
}
idSet.Add(msgID)
idSetWithContext.Add(msgID)
if s.opts.AfterContext > 0 {
for i := 0; i < s.opts.AfterContext+MaxContext; i++ {
afterID := msgID + chat1.MessageID(i+1)
idSetWithContext.Add(afterID)
}
}
}
msgIDSlice := msgIDsFromSet(idSetWithContext)
reason := chat1.GetThreadReason_INDEXED_SEARCH
msgs, err := s.indexer.G().ChatHelper.GetMessages(ctx, s.uid, convID, msgIDSlice,
true /* resolveSupersedes*/, &reason)
if err != nil {
if utils.IsPermanentErr(err) {
return nil, nil, err
}
return nil, nil, nil
}
res := []chat1.MessageUnboxed{}
for _, msg := range msgs {
if msg.IsValidFull() && msg.IsVisible() {
res = append(res, msg)
}
}
sort.Sort(utils.ByMsgUnboxedMsgID(res))
return idSet, res, nil
}
// searchHitsFromMsgIDs packages the search hit with context (nearby search
// messages) and match info (for UI highlighting). Results are ordered desc by
// msg id.
func (s *searchSession) searchHitsFromMsgIDs(ctx context.Context, conv types.RemoteConversation,
msgIDs []chat1.MessageID) (convHits *chat1.ChatSearchInboxHit, err error) {
convID := conv.GetConvID()
defer s.indexer.Trace(ctx, &err,
fmt.Sprintf("searchHitsFromMsgIDs convID: %s msgIDs: %d", convID, len(msgIDs)))()
if msgIDs == nil {
return nil, nil
}
// pull the messages in batches, short circuiting if we meet the search
// opts criteria.
var hits []chat1.ChatSearchHit
for i := 0; i < len(msgIDs); i += s.opts.MaxHits {
var batch []chat1.MessageID
if i+s.opts.MaxHits > len(msgIDs) {
batch = msgIDs[i:]
} else {
batch = msgIDs[i : i+s.opts.MaxHits]
}
hits, err = s.searchHitBatch(ctx, convID, batch, hits)
if err != nil {
return nil, err
}
if len(hits) >= s.opts.MaxHits {
break
}
}
if len(hits) == 0 {
return nil, nil
}
return &chat1.ChatSearchInboxHit{
ConvID: convID,
TeamType: conv.GetTeamType(),
ConvName: utils.GetRemoteConvDisplayName(conv),
Hits: hits,
Time: hits[0].HitMessage.Valid().Ctime,
}, nil
}
func (s *searchSession) searchHitBatch(ctx context.Context, convID chat1.ConversationID, msgIDs []chat1.MessageID,
hits []chat1.ChatSearchHit) (res []chat1.ChatSearchHit, err error) {
idSet, msgs, err := s.getMsgsAndIDSet(ctx, convID, msgIDs)
if err != nil {
return nil, err
}
for i, msg := range msgs {
if idSet.Contains(msg.GetMessageID()) && msg.IsValidFull() && s.opts.Matches(msg) {
var afterMessages, beforeMessages []chat1.UIMessage
if s.opts.AfterContext > 0 {
afterLimit := i - s.opts.AfterContext
if afterLimit < 0 {
afterLimit = 0
}
afterMessages = getUIMsgs(ctx, s.indexer.G(), convID, s.uid, msgs[afterLimit:i])
}
if s.opts.BeforeContext > 0 && i < len(msgs)-1 {
beforeLimit := i + 1 + s.opts.BeforeContext
if beforeLimit >= len(msgs) {
beforeLimit = len(msgs)
}
beforeMessages = getUIMsgs(ctx, s.indexer.G(), convID, s.uid, msgs[i+1:beforeLimit])
}
matches := searchMatches(msg, s.queryRe)
searchHit := chat1.ChatSearchHit{
BeforeMessages: beforeMessages,
HitMessage: utils.PresentMessageUnboxed(ctx, s.indexer.G(), msg, s.uid, convID),
AfterMessages: afterMessages,
Matches: matches,
}
hits = append(hits, searchHit)
if len(hits) >= s.opts.MaxHits {
break
}
}
}
return hits, nil
}
func (s *searchSession) convFullyIndexed(ctx context.Context, conv chat1.Conversation) (bool, error) {
md, err := s.indexer.store.GetMetadata(ctx, conv.GetConvID())
if err != nil {
return false, err
}
return md.FullyIndexed(conv), nil
}
func (s *searchSession) updateInboxIndex(ctx context.Context, conv chat1.Conversation) {
if err := s.indexer.store.Flush(); err != nil {
s.indexer.Debug(ctx, "updateInboxIndex: failed to flush: %s", err)
}
md, err := s.indexer.store.GetMetadata(ctx, conv.GetConvID())
if err != nil {
s.indexer.Debug(ctx, "updateInboxIndex: unable to GetMetadata %v", err)
return
}
s.inboxIndexStatus.addConv(md, conv)
}
func (s *searchSession) percentIndexed() int {
return s.inboxIndexStatus.percentIndexed()
}
func (s *searchSession) reindexConvWithUIUpdate(ctx context.Context, rconv types.RemoteConversation) error {
conv := rconv.Conv
if _, err := s.indexer.reindexConv(ctx, rconv, 0, s.inboxIndexStatus); err != nil {
return err
}
s.updateInboxIndex(ctx, conv)
if _, err := s.inboxIndexStatus.updateUI(ctx); err != nil {
s.indexer.Debug(ctx, "unable to update ui %v", err)
}
return nil
}
func (s *searchSession) searchConvWithUIUpdate(ctx context.Context, convID chat1.ConversationID) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
conv := s.getConv(convID)
msgIDs, err := s.searchConv(ctx, convID)
if err != nil {
return err
}
s.incrementNumConvsSearched()
hits, err := s.searchHitsFromMsgIDs(ctx, conv, msgIDs)
if err != nil {
return err
}
if len(msgIDs) != hits.Size() {
s.indexer.Debug(ctx, "Search: hit mismatch, found %d msgIDs in index, %d hits in conv: %v, %v",
len(msgIDs), hits.Size(), utils.GetRemoteConvDisplayName(conv), conv.ConvIDStr)
}
if hits == nil {
return nil
}
hits.Query = s.origQuery
if s.hitUICh != nil {
// Stream search hits back to the UI channel
select {
case <-ctx.Done():
return ctx.Err()
default:
}
s.hitUICh <- *hits
}
s.setHit(convID, *hits)
return nil
}
func (s *searchSession) searchDone(ctx context.Context, stage string) bool {
s.Lock()
defer s.Unlock()
if s.opts.MaxConvsSearched > 0 && s.numConvsSearched >= s.opts.MaxConvsSearched {
s.indexer.Debug(ctx, "Search: [%s] max search convs reached", stage)
return true
}
if s.opts.MaxConvsHit > 0 && len(s.hitMap) >= s.opts.MaxConvsHit {
s.indexer.Debug(ctx, "Search: [%s] max hit convs reached", stage)
return true
}
return false
}
// preSearch is the first pipeline stage, blocking on reindexing conversations
// if PRESEARCH_SYNC is set. As conversations are processed they are passed to
// the `search` stage via `preSearchCh`.
func (s *searchSession) preSearch(ctx context.Context) (err error) {
defer s.indexer.Trace(ctx, &err, "searchSession.preSearch")()
for _, conv := range s.convList {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
s.updateInboxIndex(ctx, conv.Conv)
switch s.opts.ReindexMode {
case chat1.ReIndexingMode_POSTSEARCH_SYNC:
fullyIndexed, err := s.convFullyIndexed(ctx, conv.Conv)
if err != nil || !fullyIndexed {
if err != nil {
s.indexer.Debug(ctx, "Search: failed to compute full indexed: %s", err)
}
s.reindexConvs = append(s.reindexConvs, conv.GetConvID())
}
default:
// Nothing to do for other modes.
}
}
percentIndexed, err := s.inboxIndexStatus.updateUI(ctx)
if err != nil {
return err
}
s.indexer.Debug(ctx, "Search: percent: %d", percentIndexed)
for _, conv := range s.convList {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
switch s.opts.ReindexMode {
case chat1.ReIndexingMode_PRESEARCH_SYNC:
if err := s.reindexConvWithUIUpdate(ctx, conv); err != nil {
s.indexer.Debug(ctx, "Search: Unable to reindexConv: %v, %v, %v",
utils.GetRemoteConvDisplayName(conv), conv.GetConvID(), err)
s.inboxIndexStatus.rmConv(conv.Conv)
continue
}
s.updateInboxIndex(ctx, conv.Conv)
default:
// Nothing to do for other modes.
}
}
return nil
}
// search performs the actual search on each conversation after it completes
// preSearch via `preSearchCh`
func (s *searchSession) search(ctx context.Context) (err error) {
defer s.indexer.Trace(ctx, &err, "searchSession.search")()
for _, conv := range s.convList {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
if err := s.searchConvWithUIUpdate(ctx, conv.GetConvID()); err != nil {
return err
}
if s.searchDone(ctx, "search") {
return nil
}
}
return nil
}
// postSearch is the final pipeline stage, reindexing conversations if
// POSTSEARCH_SYNC is set.
func (s *searchSession) postSearch(ctx context.Context) (err error) {
defer s.indexer.Trace(ctx, &err, "searchSession.postSearch")()
switch s.opts.ReindexMode {
case chat1.ReIndexingMode_POSTSEARCH_SYNC:
default:
return nil
}
for _, convID := range s.reindexConvs {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
conv := s.getConv(convID)
// ignore any fully indexed convs since we respect
// opts.MaxConvsSearched
fullyIndexed, err := s.convFullyIndexed(ctx, conv.Conv)
if err != nil {
return err
}
if fullyIndexed {
continue
}
if err := s.reindexConvWithUIUpdate(ctx, conv); err != nil {
s.indexer.Debug(ctx, "Search: postSearch: error reindexing: conv: %v convID: %v err: %v",
utils.GetRemoteConvDisplayName(conv), conv.ConvIDStr, err)
s.inboxIndexStatus.rmConv(conv.Conv)
continue
}
if s.searchDone(ctx, "postSearch") {
continue
}
if err := s.searchConvWithUIUpdate(ctx, convID); err != nil {
return err
}
}
return nil
}
func (s *searchSession) initRun(ctx context.Context) (shouldRun bool, err error) {
s.Lock()
defer s.Unlock()
s.tokens = tokenize(s.query)
if s.tokens == nil {
return false, nil
}
s.queryRe, err = utils.GetQueryRe(s.query)
if err != nil {
return false, err
}
s.convMap, err = s.indexer.allConvs(ctx, s.opts.ConvID)
if err != nil {
return false, err
}
s.convList = s.indexer.convsPrioritySorted(ctx, s.convMap)
if len(s.convList) == 0 {
return false, nil
}
return true, nil
}
func (s *searchSession) run(ctx context.Context) (res *chat1.ChatSearchInboxResults, err error) {
defer func() {
if err != nil {
s.Lock()
s.indexer.Debug(ctx, "search aborted, %v %d hits, %d%% percentIndexed, %d indexableConvs, %d convs searched, opts: %+v",
err, len(s.hitMap), s.percentIndexed(), s.inboxIndexStatus.numConvs(), s.numConvsSearched, s.opts)
s.Unlock()
}
}()
if shouldRun, err := s.initRun(ctx); !shouldRun || err != nil {
return nil, err
}
if err := s.preSearch(ctx); err != nil {
return nil, err
}
if err := s.search(ctx); err != nil {
return nil, err
}
if err := s.postSearch(ctx); err != nil {
return nil, err
}
s.Lock()
defer s.Unlock()
hits := make([]chat1.ChatSearchInboxHit, len(s.hitMap))
index := 0
for _, hit := range s.hitMap {
hits[index] = hit
index++
}
percentIndexed := s.percentIndexed()
res = &chat1.ChatSearchInboxResults{
Hits: hits,
PercentIndexed: percentIndexed,
}
s.indexer.Debug(ctx, "search completed, %d hits, %d%% percentIndexed, %d indexableConvs, %d convs searched, opts: %+v",
len(hits), percentIndexed, s.inboxIndexStatus.numConvs(), s.numConvsSearched, s.opts)
return res, nil
}