forked from keybase/client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinboxsource.go
1485 lines (1317 loc) · 50.7 KB
/
inboxsource.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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package chat
import (
"errors"
"fmt"
"sort"
"strings"
"time"
"github.com/keybase/client/go/chat/globals"
"github.com/keybase/client/go/chat/storage"
"github.com/keybase/client/go/chat/types"
"github.com/keybase/client/go/chat/utils"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/protocol/chat1"
"github.com/keybase/client/go/protocol/gregor1"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/client/go/teams"
"github.com/keybase/client/go/uidmap"
context "golang.org/x/net/context"
"golang.org/x/sync/errgroup"
)
type localizerPipeline struct {
globals.Contextified
utils.DebugLabeler
offline bool
superXform supersedesTransform
}
func newLocalizerPipeline(g *globals.Context, superXform supersedesTransform) *localizerPipeline {
return &localizerPipeline{
Contextified: globals.NewContextified(g),
DebugLabeler: utils.NewDebugLabeler(g.GetLog(), "localizerPipeline", false),
superXform: superXform,
}
}
type baseLocalizer struct {
globals.Contextified
utils.DebugLabeler
}
func newBaseLocalizer(g *globals.Context) *baseLocalizer {
return &baseLocalizer{
Contextified: globals.NewContextified(g),
DebugLabeler: utils.NewDebugLabeler(g.GetLog(), "baseLocalizer", false),
}
}
func (b *baseLocalizer) filterSelfFinalized(ctx context.Context, inbox types.Inbox) (res types.Inbox) {
username := b.G().Env.GetUsername().String()
res = inbox
res.ConvsUnverified = nil
for _, conv := range inbox.ConvsUnverified {
if conv.Conv.GetMembersType() == chat1.ConversationMembersType_KBFS &&
conv.Conv.GetFinalizeInfo() != nil &&
// If reset user is the current user, or is blank (only way such a thing could be in our
// inbox is if the current user is the one that reset)
(conv.Conv.GetFinalizeInfo().ResetUser == username ||
conv.Conv.GetFinalizeInfo().ResetUser == "") {
b.Debug(ctx, "baseLocalizer: skipping own finalized convo: %s name: %s", conv.GetConvID())
continue
}
res.ConvsUnverified = append(res.ConvsUnverified, conv)
}
return res
}
type BlockingLocalizer struct {
globals.Contextified
*baseLocalizer
pipeline *localizerPipeline
}
func NewBlockingLocalizer(g *globals.Context) *BlockingLocalizer {
return &BlockingLocalizer{
Contextified: globals.NewContextified(g),
baseLocalizer: newBaseLocalizer(g),
pipeline: newLocalizerPipeline(g,
newBasicSupersedesTransform(g, basicSupersedesTransformOpts{})),
}
}
func (b *BlockingLocalizer) SetOffline() {
b.pipeline.offline = true
}
func (b *BlockingLocalizer) Localize(ctx context.Context, uid gregor1.UID, inbox types.Inbox) (res []chat1.ConversationLocal, err error) {
inbox = b.filterSelfFinalized(ctx, inbox)
res, err = b.pipeline.localizeConversationsPipeline(ctx, uid, utils.PluckConvs(inbox.ConvsUnverified),
nil, nil)
if err != nil {
return res, err
}
return res, nil
}
func (b *BlockingLocalizer) Name() string {
return "blocking"
}
type NonblockInboxResult struct {
Conv chat1.Conversation
Err *chat1.ConversationErrorLocal
ConvRes *chat1.ConversationLocal
InboxRes *types.Inbox
}
type NonblockingLocalizer struct {
globals.Contextified
utils.DebugLabeler
*baseLocalizer
pipeline *localizerPipeline
localizeCb chan NonblockInboxResult
maxUnbox *int
}
func NewNonblockingLocalizer(g *globals.Context, localizeCb chan NonblockInboxResult,
maxUnbox *int) *NonblockingLocalizer {
return &NonblockingLocalizer{
Contextified: globals.NewContextified(g),
DebugLabeler: utils.NewDebugLabeler(g.GetLog(), "NonblockingLocalizer", false),
baseLocalizer: newBaseLocalizer(g),
pipeline: newLocalizerPipeline(g,
newBasicSupersedesTransform(g, basicSupersedesTransformOpts{})),
localizeCb: localizeCb,
maxUnbox: maxUnbox,
}
}
func (b *NonblockingLocalizer) SetOffline() {
b.pipeline.offline = true
}
func (b *NonblockingLocalizer) filterInboxRes(ctx context.Context, inbox types.Inbox, uid gregor1.UID) types.Inbox {
defer b.Trace(ctx, func() error { return nil }, "filterInboxRes")()
// Loop through and look for empty convs or known errors and skip them
var res []types.RemoteConversation
for _, conv := range inbox.ConvsUnverified {
if utils.IsConvEmpty(conv.Conv) {
b.Debug(ctx, "filterInboxRes: skipping because empty: convID: %s", conv.Conv.GetConvID())
continue
}
res = append(res, conv)
}
return types.Inbox{
Version: inbox.Version,
ConvsUnverified: res,
Convs: inbox.Convs,
Pagination: inbox.Pagination,
}
}
func (b *NonblockingLocalizer) Localize(ctx context.Context, uid gregor1.UID, inbox types.Inbox) (res []chat1.ConversationLocal, err error) {
defer b.Trace(ctx, func() error { return err }, "Localize")()
// Run some easy filters for empty messages and known errors to optimize UI drawing behavior
inbox = b.filterSelfFinalized(ctx, inbox)
filteredInbox := b.filterInboxRes(ctx, inbox, uid)
// Send inbox over localize channel
b.localizeCb <- NonblockInboxResult{
InboxRes: &filteredInbox,
}
// Spawn off localization into its own goroutine and use cb to communicate with outside world
bctx := BackgroundContext(ctx, b.G())
go func() {
b.Debug(bctx, "Localize: starting background localization: convs: %d",
len(inbox.ConvsUnverified))
b.pipeline.localizeConversationsPipeline(bctx, uid, utils.PluckConvs(inbox.ConvsUnverified),
b.maxUnbox, &b.localizeCb)
// Shutdown localize channel
close(b.localizeCb)
}()
return nil, nil
}
func (b *NonblockingLocalizer) Name() string {
return "nonblocking"
}
func filterConvLocals(convLocals []chat1.ConversationLocal, rquery *chat1.GetInboxQuery,
query *chat1.GetInboxLocalQuery, nameInfo *types.NameInfoUntrusted) (res []chat1.ConversationLocal, err error) {
for _, convLocal := range convLocals {
if rquery != nil && rquery.TlfID != nil {
// inbox query contained a TLF name, so check to make sure that
// the conversation from the server matches tlfInfo from kbfs
if convLocal.Info.TLFNameExpanded() != nameInfo.CanonicalName {
if convLocal.Error == nil {
return nil, fmt.Errorf("server conversation TLF name mismatch: %s, expected %s",
convLocal.Info.TLFNameExpanded(), nameInfo.CanonicalName)
}
}
if convLocal.Info.Visibility != rquery.Visibility() {
return nil, fmt.Errorf("server conversation TLF visibility mismatch: %s, expected %s",
convLocal.Info.Visibility, rquery.Visibility())
}
if !nameInfo.ID.Eq(convLocal.Info.Triple.Tlfid) {
return nil, fmt.Errorf("server conversation TLF ID mismatch: %s, expected %s",
convLocal.Info.Triple.Tlfid, nameInfo.ID)
}
// tlfInfo.ID and rquery.TlfID should always match, but just in case:
if !rquery.TlfID.Eq(convLocal.Info.Triple.Tlfid) {
return nil, fmt.Errorf("server conversation TLF ID mismatch: %s, expected %s",
convLocal.Info.Triple.Tlfid, rquery.TlfID)
}
// Note that previously, we made a call to KBFS to lookup the TLF in
// convLocal.Info.TlfName and verify that, but the above checks accomplish
// the same thing without an RPC call.
}
// server can't query on topic name, so we have to do it ourselves in the loop
if query != nil && query.TopicName != nil && *query.TopicName != convLocal.Info.TopicName {
continue
}
res = append(res, convLocal)
}
return res, nil
}
type baseInboxSource struct {
globals.Contextified
utils.DebugLabeler
types.InboxSource
getChatInterface func() chat1.RemoteInterface
}
func newBaseInboxSource(g *globals.Context, ibs types.InboxSource,
getChatInterface func() chat1.RemoteInterface) *baseInboxSource {
return &baseInboxSource{
Contextified: globals.NewContextified(g),
InboxSource: ibs,
DebugLabeler: utils.NewDebugLabeler(g.GetLog(), "baseInboxSource", false),
getChatInterface: getChatInterface,
}
}
func (b *baseInboxSource) notifyTlfFinalize(ctx context.Context, username string) {
// Let the rest of the system know this user has changed
arg := libkb.NewLoadUserArg(b.G().ExternalG()).WithName(username).WithPublicKeyOptional()
finalizeUser, err := libkb.LoadUser(arg)
if err != nil {
b.Debug(ctx, "notifyTlfFinalize: failed to load finalize user, skipping user changed notification: err: %s", err.Error())
} else {
b.G().UserChanged(finalizeUser.GetUID())
}
}
func (b *baseInboxSource) SetRemoteInterface(ri func() chat1.RemoteInterface) {
b.getChatInterface = ri
}
func (b *baseInboxSource) GetInboxQueryLocalToRemote(ctx context.Context,
lquery *chat1.GetInboxLocalQuery) (rquery *chat1.GetInboxQuery, info *types.NameInfoUntrusted, err error) {
if lquery == nil {
return nil, info, nil
}
rquery = &chat1.GetInboxQuery{}
if lquery.Name != nil && len(lquery.Name.Name) > 0 {
var err error
tlfName := utils.AddUserToTLFName(b.G(), lquery.Name.Name, lquery.Visibility(),
lquery.Name.MembersType)
info, err = CreateNameInfoSource(ctx, b.G(), lquery.Name.MembersType).LookupIDUntrusted(ctx, tlfName,
lquery.Visibility() == keybase1.TLFVisibility_PUBLIC)
if err != nil {
b.Debug(ctx, "GetInboxQueryLocalToRemote: failed: %s", err)
return nil, info, err
}
rquery.TlfID = &info.ID
rquery.MembersTypes = []chat1.ConversationMembersType{lquery.Name.MembersType}
b.Debug(ctx, "GetInboxQueryLocalToRemote: mapped name %q to TLFID %v", tlfName, info.ID)
}
rquery.After = lquery.After
rquery.Before = lquery.Before
rquery.TlfVisibility = lquery.TlfVisibility
rquery.TopicType = lquery.TopicType
rquery.UnreadOnly = lquery.UnreadOnly
rquery.ReadOnly = lquery.ReadOnly
rquery.ComputeActiveList = lquery.ComputeActiveList
rquery.ConvIDs = lquery.ConvIDs
rquery.OneChatTypePerTLF = lquery.OneChatTypePerTLF
rquery.Status = lquery.Status
rquery.SummarizeMaxMsgs = false
return rquery, info, nil
}
func (b *baseInboxSource) IsMember(ctx context.Context, uid gregor1.UID, convID chat1.ConversationID) (bool, error) {
ib, err := b.ReadUnverified(ctx, uid, true, &chat1.GetInboxQuery{
ConvID: &convID,
}, nil)
if err != nil {
return false, err
}
if len(ib.ConvsUnverified) == 0 {
return false, fmt.Errorf("conversation not found: %s", convID)
}
conv := ib.ConvsUnverified[0]
switch conv.Conv.ReaderInfo.Status {
case chat1.ConversationMemberStatus_ACTIVE, chat1.ConversationMemberStatus_RESET:
return true, nil
default:
return false, nil
}
}
func GetInboxQueryNameInfo(ctx context.Context, g *globals.Context,
lquery *chat1.GetInboxLocalQuery) (*types.NameInfoUntrusted, error) {
if lquery.Name == nil || len(lquery.Name.Name) == 0 {
return nil, nil
}
return CreateNameInfoSource(ctx, g, lquery.Name.MembersType).LookupIDUntrusted(ctx, lquery.Name.Name,
lquery.Visibility() == keybase1.TLFVisibility_PUBLIC)
}
type RemoteInboxSource struct {
globals.Contextified
utils.DebugLabeler
*baseInboxSource
*sourceOfflinable
}
var _ types.InboxSource = (*RemoteInboxSource)(nil)
func NewRemoteInboxSource(g *globals.Context, ri func() chat1.RemoteInterface) *RemoteInboxSource {
labeler := utils.NewDebugLabeler(g.GetLog(), "RemoteInboxSource", false)
s := &RemoteInboxSource{
Contextified: globals.NewContextified(g),
DebugLabeler: labeler,
sourceOfflinable: newSourceOfflinable(g, labeler),
}
s.baseInboxSource = newBaseInboxSource(g, s, ri)
return s
}
func (s *RemoteInboxSource) Read(ctx context.Context, uid gregor1.UID,
localizer types.ChatLocalizer, useLocalData bool, query *chat1.GetInboxLocalQuery,
p *chat1.Pagination) (types.Inbox, error) {
if localizer == nil {
localizer = NewBlockingLocalizer(s.G())
}
if s.IsOffline(ctx) {
localizer.SetOffline()
}
s.Debug(ctx, "Read: using localizer: %s", localizer.Name())
rquery, tlfInfo, err := s.GetInboxQueryLocalToRemote(ctx, query)
if err != nil {
return types.Inbox{}, err
}
inbox, err := s.ReadUnverified(ctx, uid, useLocalData, rquery, p)
if err != nil {
return types.Inbox{}, err
}
res, err := localizer.Localize(ctx, uid, inbox)
if err != nil {
return types.Inbox{}, err
}
res, err = filterConvLocals(res, rquery, query, tlfInfo)
if err != nil {
return types.Inbox{}, err
}
return types.Inbox{
Version: inbox.Version,
Convs: res,
ConvsUnverified: inbox.ConvsUnverified,
Pagination: inbox.Pagination,
}, nil
}
func (s *RemoteInboxSource) ReadUnverified(ctx context.Context, uid gregor1.UID, useLocalData bool,
rquery *chat1.GetInboxQuery, p *chat1.Pagination) (types.Inbox, error) {
if s.IsOffline(ctx) {
return types.Inbox{}, OfflineError{}
}
ib, err := s.getChatInterface().GetInboxRemote(ctx, chat1.GetInboxRemoteArg{
Query: rquery,
Pagination: p,
})
if err != nil {
return types.Inbox{}, err
}
return types.Inbox{
Version: ib.Inbox.Full().Vers,
ConvsUnverified: utils.RemoteConvs(ib.Inbox.Full().Conversations),
Pagination: ib.Inbox.Full().Pagination,
}, nil
}
func (s *RemoteInboxSource) NewConversation(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
conv chat1.Conversation) error {
return nil
}
func (s *RemoteInboxSource) NewMessage(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
convID chat1.ConversationID, msg chat1.MessageBoxed, maxMsgs []chat1.MessageSummary) (*chat1.ConversationLocal, error) {
return nil, nil
}
func (s *RemoteInboxSource) ReadMessage(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
convID chat1.ConversationID, msgID chat1.MessageID) (*chat1.ConversationLocal, error) {
return nil, nil
}
func (s *RemoteInboxSource) SetStatus(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
convID chat1.ConversationID, status chat1.ConversationStatus) (*chat1.ConversationLocal, error) {
return nil, nil
}
func (s *RemoteInboxSource) SetAppNotificationSettings(ctx context.Context, uid gregor1.UID,
vers chat1.InboxVers, convID chat1.ConversationID, settings chat1.ConversationNotificationInfo) (*chat1.ConversationLocal, error) {
return nil, nil
}
func (s *RemoteInboxSource) TlfFinalize(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
convIDs []chat1.ConversationID, finalizeInfo chat1.ConversationFinalizeInfo) ([]chat1.ConversationLocal, error) {
// Notify rest of system about reset
s.notifyTlfFinalize(ctx, finalizeInfo.ResetUser)
return nil, nil
}
func (s *RemoteInboxSource) MembershipUpdate(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
joined []chat1.ConversationMember, removed []chat1.ConversationMember, resets []chat1.ConversationMember,
previews []chat1.ConversationID) (res types.MembershipUpdateRes, err error) {
return res, err
}
func (s *RemoteInboxSource) Expunge(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers, convID chat1.ConversationID,
expunge chat1.Expunge, maxMsgs []chat1.MessageSummary) (res *chat1.ConversationLocal, err error) {
return res, err
}
func (s *RemoteInboxSource) SetConvRetention(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
convID chat1.ConversationID, policy chat1.RetentionPolicy) (res *chat1.ConversationLocal, err error) {
return res, err
}
func (s *RemoteInboxSource) SetTeamRetention(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
teamID keybase1.TeamID, policy chat1.RetentionPolicy) (res []chat1.ConversationLocal, err error) {
return res, err
}
func (s *RemoteInboxSource) SetConvSettings(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
convID chat1.ConversationID, convSettings *chat1.ConversationSettings) (res *chat1.ConversationLocal, err error) {
return res, err
}
func (s *RemoteInboxSource) TeamTypeChanged(ctx context.Context, uid gregor1.UID,
vers chat1.InboxVers, convID chat1.ConversationID, teamType chat1.TeamType) (conv *chat1.ConversationLocal, err error) {
return conv, err
}
func (s *RemoteInboxSource) UpdateKBFSToImpteam(ctx context.Context, uid gregor1.UID,
vers chat1.InboxVers, convID chat1.ConversationID) (conv *chat1.ConversationLocal, err error) {
return conv, err
}
type HybridInboxSource struct {
globals.Contextified
utils.DebugLabeler
*baseInboxSource
*sourceOfflinable
}
var _ types.InboxSource = (*HybridInboxSource)(nil)
func NewHybridInboxSource(g *globals.Context,
getChatInterface func() chat1.RemoteInterface) *HybridInboxSource {
labeler := utils.NewDebugLabeler(g.GetLog(), "HybridInboxSource", false)
s := &HybridInboxSource{
Contextified: globals.NewContextified(g),
DebugLabeler: labeler,
sourceOfflinable: newSourceOfflinable(g, labeler),
}
s.baseInboxSource = newBaseInboxSource(g, s, getChatInterface)
return s
}
func (s *HybridInboxSource) fetchRemoteInbox(ctx context.Context, uid gregor1.UID, query *chat1.GetInboxQuery,
p *chat1.Pagination) (types.Inbox, error) {
// Insta fail if we are offline
if s.IsOffline(ctx) {
return types.Inbox{}, OfflineError{}
}
// We always want this on for fetches to fill the local inbox, otherwise we never get the
// full list for the conversations that come back
var rquery chat1.GetInboxQuery
if query == nil {
rquery = chat1.GetInboxQuery{
ComputeActiveList: true,
SummarizeMaxMsgs: false,
}
} else {
rquery = *query
rquery.ComputeActiveList = true
// If we have been given a fixed set of conversation IDs, then just return summary, since
// we likely have the messages cached locally.
rquery.SummarizeMaxMsgs = len(rquery.ConvIDs) > 0 || rquery.ConvID != nil
}
ib, err := s.getChatInterface().GetInboxRemote(ctx, chat1.GetInboxRemoteArg{
Query: &rquery,
Pagination: p,
})
if err != nil {
return types.Inbox{}, err
}
for index, conv := range ib.Inbox.Full().Conversations {
// Retention policy expunge
expunge := conv.GetExpunge()
if expunge != nil {
s.G().ConvSource.Expunge(ctx, conv.GetConvID(), uid, *expunge)
}
// Queue all these convs up to be loaded by the background loader
// Only load first 100 so we don't get the conv loader too backed up
if index < 100 {
job := types.NewConvLoaderJob(conv.GetConvID(), &chat1.Pagination{Num: 50},
types.ConvLoaderPriorityMedium, newConvLoaderPagebackHook(s.G(), 0, 5))
if err := s.G().ConvLoader.Queue(ctx, job); err != nil {
s.Debug(ctx, "fetchRemoteInbox: failed to queue conversation load: %s", err)
}
}
}
return types.Inbox{
Version: ib.Inbox.Full().Vers,
ConvsUnverified: utils.RemoteConvs(ib.Inbox.Full().Conversations),
Pagination: ib.Inbox.Full().Pagination,
}, nil
}
func (s *HybridInboxSource) Read(ctx context.Context, uid gregor1.UID,
localizer types.ChatLocalizer, useLocalData bool, query *chat1.GetInboxLocalQuery,
p *chat1.Pagination) (inbox types.Inbox, err error) {
defer s.Trace(ctx, func() error { return err }, "Read")()
if localizer == nil {
localizer = NewBlockingLocalizer(s.G())
}
if s.IsOffline(ctx) {
localizer.SetOffline()
}
s.Debug(ctx, "Read: using localizer: %s", localizer.Name())
// Read unverified inbox
rquery, tlfInfo, err := s.GetInboxQueryLocalToRemote(ctx, query)
if err != nil {
return inbox, err
}
inbox, err = s.ReadUnverified(ctx, uid, useLocalData, rquery, p)
if err != nil {
return inbox, err
}
// Localize
inbox.Convs, err = localizer.Localize(ctx, uid, inbox)
if err != nil {
return inbox, err
}
// Run post filters
inbox.Convs, err = filterConvLocals(inbox.Convs, rquery, query, tlfInfo)
if err != nil {
return inbox, err
}
// Write metadata to the inbox cache
if err = storage.NewInbox(s.G(), uid).MergeLocalMetadata(ctx, inbox.Convs); err != nil {
// Don't abort the operation on this kind of error
s.Debug(ctx, "Read: unable to write inbox local metadata: %s", err)
}
return inbox, nil
}
func (s *HybridInboxSource) ReadUnverified(ctx context.Context, uid gregor1.UID, useLocalData bool,
query *chat1.GetInboxQuery, p *chat1.Pagination) (res types.Inbox, err error) {
defer s.Trace(ctx, func() error { return err }, "ReadUnverified")()
var cerr storage.Error
inboxStore := storage.NewInbox(s.G(), uid)
// Try local storage (if enabled)
if useLocalData {
var vers chat1.InboxVers
var convs []types.RemoteConversation
var pagination *chat1.Pagination
vers, convs, pagination, cerr = inboxStore.Read(ctx, query, p)
if cerr == nil {
s.Debug(ctx, "ReadUnverified: hit local storage: uid: %s convs: %d", uid, len(convs))
res = types.Inbox{
Version: vers,
ConvsUnverified: convs,
Pagination: pagination,
}
}
} else {
cerr = storage.MissError{}
}
// If we hit an error reading from storage, then read from remote
if cerr != nil {
if _, ok := cerr.(storage.MissError); !ok {
s.Debug(ctx, "ReadUnverified: error fetching inbox: %s", cerr.Error())
} else {
s.Debug(ctx, "ReadUnverified: storage miss")
}
// Go to the remote on miss
res, err = s.fetchRemoteInbox(ctx, uid, query, p)
if err != nil {
return res, err
}
// Write out to local storage only if we are using local data
if useLocalData {
if cerr = inboxStore.Merge(ctx, res.Version, utils.PluckConvs(res.ConvsUnverified), query, p); cerr != nil {
s.Debug(ctx, "ReadUnverified: failed to write inbox to local storage: %s", cerr.Error())
}
}
}
return res, err
}
func (s *HybridInboxSource) handleInboxError(ctx context.Context, err error, uid gregor1.UID) (ferr error) {
defer func() {
if ferr != nil {
// Only do this aggressive clear if the error we get is not some kind of network error
if IsOfflineError(ferr) == OfflineErrorKindOnline {
s.Debug(ctx, "handleInboxError: failed to recover from inbox error, clearing: %s", ferr)
storage.NewInbox(s.G(), uid).Clear(ctx)
} else {
s.Debug(ctx, "handleInboxError: skipping inbox clear because of offline error: %s", ferr)
}
}
}()
if _, ok := err.(storage.MissError); ok {
return nil
}
if verr, ok := err.(storage.VersionMismatchError); ok {
s.Debug(ctx, "handleInboxError: version mismatch, syncing and sending stale notifications: %s",
verr.Error())
return s.G().Syncer.Sync(ctx, s.getChatInterface(), uid, nil)
}
return err
}
func (s *HybridInboxSource) NewConversation(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
conv chat1.Conversation) (err error) {
defer s.Trace(ctx, func() error { return err }, "NewConversation")()
if cerr := storage.NewInbox(s.G(), uid).NewConversation(ctx, vers, conv); cerr != nil {
err = s.handleInboxError(ctx, cerr, uid)
return err
}
return nil
}
func (s *HybridInboxSource) getConvLocal(ctx context.Context, uid gregor1.UID,
convID chat1.ConversationID) (conv *chat1.ConversationLocal, err error) {
// Read back affected conversation so we can send it to the frontend
ib, err := s.Read(ctx, uid, nil, true, &chat1.GetInboxLocalQuery{
ConvIDs: []chat1.ConversationID{convID},
}, nil)
if err != nil {
return conv, err
}
if len(ib.Convs) == 0 {
return conv, fmt.Errorf("unable to find conversation for new message: convID: %s", convID)
}
if len(ib.Convs) > 1 {
return conv, fmt.Errorf("more than one conversation returned? convID: %s", convID)
}
return &ib.Convs[0], nil
}
// Get convs. May return fewer or no conversations.
func (s *HybridInboxSource) getConvsLocal(ctx context.Context, uid gregor1.UID,
convIDs []chat1.ConversationID) ([]chat1.ConversationLocal, error) {
// Read back affected conversation so we can send it to the frontend
ib, err := s.Read(ctx, uid, nil, true, &chat1.GetInboxLocalQuery{
ConvIDs: convIDs,
}, nil)
return ib.Convs, err
}
func (s *HybridInboxSource) NewMessage(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
convID chat1.ConversationID, msg chat1.MessageBoxed, maxMsgs []chat1.MessageSummary) (conv *chat1.ConversationLocal, err error) {
defer s.Trace(ctx, func() error { return err }, "NewMessage")()
if cerr := storage.NewInbox(s.G(), uid).NewMessage(ctx, vers, convID, msg, maxMsgs); cerr != nil {
err = s.handleInboxError(ctx, cerr, uid)
return nil, err
}
if conv, err = s.getConvLocal(ctx, uid, convID); err != nil {
s.Debug(ctx, "NewMessage: unable to load conversation: convID: %s err: %s", convID, err.Error())
return nil, nil
}
return conv, nil
}
func (s *HybridInboxSource) ReadMessage(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
convID chat1.ConversationID, msgID chat1.MessageID) (conv *chat1.ConversationLocal, err error) {
defer s.Trace(ctx, func() error { return err }, "ReadMessage")()
if cerr := storage.NewInbox(s.G(), uid).ReadMessage(ctx, vers, convID, msgID); cerr != nil {
err = s.handleInboxError(ctx, cerr, uid)
return nil, err
}
if conv, err = s.getConvLocal(ctx, uid, convID); err != nil {
s.Debug(ctx, "ReadMessage: unable to load conversation: convID: %s err: %s", convID, err.Error())
return nil, nil
}
return conv, nil
}
func (s *HybridInboxSource) SetStatus(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
convID chat1.ConversationID, status chat1.ConversationStatus) (conv *chat1.ConversationLocal, err error) {
defer s.Trace(ctx, func() error { return err }, "SetStatus")()
if cerr := storage.NewInbox(s.G(), uid).SetStatus(ctx, vers, convID, status); cerr != nil {
err = s.handleInboxError(ctx, cerr, uid)
return nil, err
}
if conv, err = s.getConvLocal(ctx, uid, convID); err != nil {
s.Debug(ctx, "SetStatus: unable to load conversation: convID: %s err: %s", convID, err.Error())
return nil, nil
}
return conv, nil
}
func (s *HybridInboxSource) SetAppNotificationSettings(ctx context.Context, uid gregor1.UID,
vers chat1.InboxVers, convID chat1.ConversationID, settings chat1.ConversationNotificationInfo) (conv *chat1.ConversationLocal, err error) {
defer s.Trace(ctx, func() error { return err }, "SetAppNotificationSettings")()
ib := storage.NewInbox(s.G(), uid)
if cerr := ib.SetAppNotificationSettings(ctx, vers, convID, settings); cerr != nil {
err = s.handleInboxError(ctx, cerr, uid)
return nil, err
}
if conv, err = s.getConvLocal(ctx, uid, convID); err != nil {
s.Debug(ctx, "SetAppNotificationSettings: unable to load conversation: convID: %s err: %s",
convID, err.Error())
return nil, nil
}
return conv, nil
}
func (s *HybridInboxSource) TeamTypeChanged(ctx context.Context, uid gregor1.UID,
vers chat1.InboxVers, convID chat1.ConversationID, teamType chat1.TeamType) (conv *chat1.ConversationLocal, err error) {
defer s.Trace(ctx, func() error { return err }, "TeamTypeChanged")()
// Read the remote conversation so we can get the notification settings changes
remoteConv, err := GetUnverifiedConv(ctx, s.G(), uid, convID, false)
if err != nil {
s.Debug(ctx, "TeamTypeChanged: failed to read team type conv: %s", err.Error())
return nil, err
}
ib := storage.NewInbox(s.G(), uid)
if cerr := ib.TeamTypeChanged(ctx, vers, convID, teamType, remoteConv.Notifications); cerr != nil {
err = s.handleInboxError(ctx, cerr, uid)
return nil, err
}
if conv, err = s.getConvLocal(ctx, uid, convID); err != nil {
s.Debug(ctx, "TeamTypeChanged: unable to load conversation: convID: %s err: %s",
convID, err.Error())
return nil, nil
}
return conv, nil
}
func (s *HybridInboxSource) UpgradeKBFSToImpteam(ctx context.Context, uid gregor1.UID,
vers chat1.InboxVers, convID chat1.ConversationID) (conv *chat1.ConversationLocal, err error) {
defer s.Trace(ctx, func() error { return err }, "UpgradeKBFSToImpteam")()
ib := storage.NewInbox(s.G(), uid)
if cerr := ib.UpgradeKBFSToImpteam(ctx, vers, convID); cerr != nil {
err = s.handleInboxError(ctx, cerr, uid)
return nil, err
}
if conv, err = s.getConvLocal(ctx, uid, convID); err != nil {
s.Debug(ctx, "UpgradeKBFSToImpteam: unable to load conversation: convID: %s err: %s",
convID, err.Error())
return nil, nil
}
return conv, nil
}
func (s *HybridInboxSource) TlfFinalize(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
convIDs []chat1.ConversationID, finalizeInfo chat1.ConversationFinalizeInfo) (convs []chat1.ConversationLocal, err error) {
defer s.Trace(ctx, func() error { return err }, "TlfFinalize")()
if cerr := storage.NewInbox(s.G(), uid).TlfFinalize(ctx, vers, convIDs, finalizeInfo); cerr != nil {
err = s.handleInboxError(ctx, cerr, uid)
return convs, err
}
for _, convID := range convIDs {
var conv *chat1.ConversationLocal
if conv, err = s.getConvLocal(ctx, uid, convID); err != nil {
s.Debug(ctx, "TlfFinalize: unable to get conversation: %s", convID)
}
if conv != nil {
convs = append(convs, *conv)
}
}
// Notify rest of system about finalize
s.notifyTlfFinalize(ctx, finalizeInfo.ResetUser)
return convs, nil
}
func (s *HybridInboxSource) MembershipUpdate(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
joined []chat1.ConversationMember, removed []chat1.ConversationMember, resets []chat1.ConversationMember,
previews []chat1.ConversationID) (res types.MembershipUpdateRes, err error) {
defer s.Trace(ctx, func() error { return err }, "MembershipUpdate")()
// Separate into joins and removed on uid, and then on other users
var userJoined []chat1.ConversationID
for _, j := range joined {
if j.Uid.Eq(uid) {
userJoined = append(userJoined, j.ConvID)
} else {
res.OthersJoinedConvs = append(res.OthersJoinedConvs, j)
}
}
// Append any previewed channels as well. We can do this since we just fetch all these conversations from
// the server, and that will have the proper member status set.
userJoined = append(userJoined, previews...)
for _, r := range removed {
if r.Uid.Eq(uid) {
// Blow away conversation cache for any conversations we get removed from
s.Debug(ctx, "MembershipUpdate: clear conv cache for removed conv: %s", r.ConvID)
s.G().ConvSource.Clear(ctx, r.ConvID, uid)
res.UserRemovedConvs = append(res.UserRemovedConvs, r)
} else {
res.OthersRemovedConvs = append(res.OthersRemovedConvs, r)
}
}
// Load the user joined conversations
var userJoinedConvs []chat1.Conversation
if len(userJoined) > 0 {
var ibox types.Inbox
ibox, err = s.Read(ctx, uid, nil, false, &chat1.GetInboxLocalQuery{
ConvIDs: userJoined,
}, nil)
if err != nil {
s.Debug(ctx, "MembershipUpdate: failed to read joined convs: %s", err.Error())
return
}
userJoinedConvs = utils.PluckConvs(ibox.ConvsUnverified)
res.UserJoinedConvs = ibox.Convs
}
for _, r := range resets {
if r.Uid.Eq(uid) {
res.UserResetConvs = append(res.UserResetConvs, r)
} else {
res.OthersResetConvs = append(res.OthersResetConvs, r)
}
}
ib := storage.NewInbox(s.G(), uid)
if cerr := ib.MembershipUpdate(ctx, vers, userJoinedConvs, res.UserRemovedConvs,
res.OthersJoinedConvs, res.OthersRemovedConvs, res.UserResetConvs, res.OthersResetConvs); cerr != nil {
err = s.handleInboxError(ctx, cerr, uid)
return res, err
}
return res, nil
}
func (s *HybridInboxSource) Expunge(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers, convID chat1.ConversationID,
expunge chat1.Expunge, maxMsgs []chat1.MessageSummary) (*chat1.ConversationLocal, error) {
return s.modConversation(ctx, "Expunge", uid, convID, func(ctx context.Context, ib *storage.Inbox) error {
return ib.Expunge(ctx, vers, convID, expunge, maxMsgs)
})
}
func (s *HybridInboxSource) SetConvRetention(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
convID chat1.ConversationID, policy chat1.RetentionPolicy) (res *chat1.ConversationLocal, err error) {
return s.modConversation(ctx, "SetConvRetention", uid, convID, func(ctx context.Context, ib *storage.Inbox) error {
return ib.SetConvRetention(ctx, vers, convID, policy)
})
}
func (s *HybridInboxSource) SetTeamRetention(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
teamID keybase1.TeamID, policy chat1.RetentionPolicy) (convs []chat1.ConversationLocal, err error) {
defer s.Trace(ctx, func() error { return err }, "SetTeamRetention")()
ib := storage.NewInbox(s.G(), uid)
convIDs, cerr := ib.SetTeamRetention(ctx, vers, teamID, policy)
if cerr != nil {
err = s.handleInboxError(ctx, cerr, uid)
return nil, err
}
if convs, err = s.getConvsLocal(ctx, uid, convIDs); err != nil {
s.Debug(ctx, "SetTeamRetention: unable to load conversations: convIDs: %v err: %s",
convIDs, err.Error())
return nil, nil
}
return convs, nil
}
func (s *HybridInboxSource) SetConvSettings(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
convID chat1.ConversationID, convSettings *chat1.ConversationSettings) (res *chat1.ConversationLocal, err error) {
return s.modConversation(ctx, "SetConvSettings", uid, convID, func(ctx context.Context, ib *storage.Inbox) error {
return ib.SetConvSettings(ctx, vers, convID, convSettings)
})
}
func (s *HybridInboxSource) modConversation(ctx context.Context, debugLabel string, uid gregor1.UID, convID chat1.ConversationID,
mod func(context.Context, *storage.Inbox) error) (
conv *chat1.ConversationLocal, err error) {
defer s.Trace(ctx, func() error { return err }, debugLabel)()
ib := storage.NewInbox(s.G(), uid)
if cerr := mod(ctx, ib); cerr != nil {
err = s.handleInboxError(ctx, cerr, uid)
return nil, err
}
if conv, err = s.getConvLocal(ctx, uid, convID); err != nil {
s.Debug(ctx, "%v: unable to load conversation: convID: %s err: %s",
debugLabel, convID, err.Error())
return nil, nil
}
return conv, nil
}
func (s *localizerPipeline) localizeConversationsPipeline(ctx context.Context, uid gregor1.UID,
convs []chat1.Conversation, maxUnbox *int, localizeCb *chan NonblockInboxResult) ([]chat1.ConversationLocal, error) {
// Fetch conversation local information in parallel
type jobRes struct {
conv chat1.ConversationLocal
index int
}
type job struct {
conv chat1.Conversation
index int
}
if maxUnbox != nil {
s.Debug(ctx, "pipeline: maxUnbox set to: %d", *maxUnbox)
}
eg, ctx := errgroup.WithContext(ctx)
convCh := make(chan job)
retCh := make(chan jobRes)
eg.Go(func() error {
defer close(convCh)
for i, conv := range convs {
if maxUnbox != nil && i >= *maxUnbox {
s.Debug(ctx, "pipeline: maxUnbox set and reached, early exit: %d",
*maxUnbox)
return nil
}
select {
case convCh <- job{conv: conv, index: i}:
case <-ctx.Done():
return ctx.Err()
}
}
return nil
})
nthreads := s.G().Env.GetChatInboxSourceLocalizeThreads()
s.Debug(ctx, "pipeline: using %d threads", nthreads)
for i := 0; i < nthreads; i++ {
eg.Go(func() error {
for conv := range convCh {
convLocal := s.localizeConversation(ctx, uid, conv.conv)
jr := jobRes{
conv: convLocal,
index: conv.index,