This repository has been archived by the owner on Jul 7, 2020. It is now read-only.
forked from keybase/client
/
server.go
2849 lines (2575 loc) · 96.6 KB
/
server.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 (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/keybase/clockwork"
"github.com/keybase/client/go/teams"
"encoding/hex"
"github.com/keybase/client/go/chat/attachments"
"github.com/keybase/client/go/chat/globals"
"github.com/keybase/client/go/chat/s3"
"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/go-framed-msgpack-rpc/rpc"
"golang.org/x/net/context"
"golang.org/x/sync/errgroup"
)
type ServerConnection interface {
Reconnect(context.Context) (bool, error)
GetClient() chat1.RemoteInterface
}
type UISource interface {
GetChatUI(sessionID int) libkb.ChatUI
GetStreamUICli() *keybase1.StreamUiClient
}
type Server struct {
globals.Contextified
utils.DebugLabeler
serverConn ServerConnection
uiSource UISource
boxer *Boxer
store *attachments.Store
identNotifier types.IdentifyNotifier
clock clockwork.Clock
convPageStatus map[string]chat1.Pagination
// Only for testing
rc chat1.RemoteInterface
mockChatUI libkb.ChatUI
cachedThreadDelay *time.Duration
remoteThreadDelay *time.Duration
}
var _ chat1.LocalInterface = (*Server)(nil)
func NewServer(g *globals.Context, store *attachments.Store, serverConn ServerConnection,
uiSource UISource) *Server {
return &Server{
Contextified: globals.NewContextified(g),
DebugLabeler: utils.NewDebugLabeler(g.GetLog(), "Server", false),
serverConn: serverConn,
uiSource: uiSource,
store: store,
boxer: NewBoxer(g),
identNotifier: NewCachingIdentifyNotifier(g),
clock: clockwork.NewRealClock(),
convPageStatus: make(map[string]chat1.Pagination),
}
}
func (h *Server) SetClock(clock clockwork.Clock) {
h.clock = clock
}
func (h *Server) getChatUI(sessionID int) libkb.ChatUI {
if h.mockChatUI != nil {
return h.mockChatUI
}
return h.uiSource.GetChatUI(sessionID)
}
func (h *Server) getStreamUICli() *keybase1.StreamUiClient {
return h.uiSource.GetStreamUICli()
}
func (h *Server) handleOfflineError(ctx context.Context, err error,
res chat1.OfflinableResult) error {
errKind := IsOfflineError(err)
if errKind != OfflineErrorKindOnline {
h.Debug(ctx, "handleOfflineError: setting offline: err: %s", err)
res.SetOffline()
switch errKind {
case OfflineErrorKindOfflineReconnect:
// Reconnect Gregor if we think we are offline (and told to reconnect)
h.Debug(ctx, "handleOfflineError: reconnecting to gregor")
if _, err := h.serverConn.Reconnect(ctx); err != nil {
h.Debug(ctx, "handleOfflineError: error reconnecting: %s", err)
} else {
h.Debug(ctx, "handleOfflineError: success reconnecting")
}
}
return nil
}
return err
}
func (h *Server) setResultRateLimit(ctx context.Context, res types.RateLimitedResult) {
res.SetRateLimits(CtxRateLimits(ctx))
}
func (h *Server) presentUnverifiedInbox(ctx context.Context, convs []types.RemoteConversation,
p *chat1.Pagination, offline bool) (res chat1.UnverifiedInboxUIItems, err error) {
for _, rawConv := range convs {
if len(rawConv.Conv.MaxMsgSummaries) == 0 {
h.Debug(ctx, "presentUnverifiedInbox: invalid convo, no max msg summaries, skipping: %s",
rawConv.Conv.GetConvID())
continue
}
res.Items = append(res.Items, utils.PresentRemoteConversation(rawConv))
}
res.Pagination = utils.PresentPagination(p)
res.Offline = offline
return res, err
}
// suspendConvLoader will suspend the global ConvLoader until the return function is called. This allows
// a succinct call like defer suspendConvLoader(ctx)() in RPC handlers wishing to lock out the
// conv loader.
func (h *Server) suspendConvLoader(ctx context.Context) func() {
if canceled := h.G().ConvLoader.Suspend(ctx); canceled {
h.Debug(ctx, "suspendConvLoader: canceled background task")
}
return func() {
h.G().ConvLoader.Resume(ctx)
}
}
func (h *Server) getUID() gregor1.UID {
return gregor1.UID(h.G().Env.GetUID().ToBytes())
}
func (h *Server) GetInboxNonblockLocal(ctx context.Context, arg chat1.GetInboxNonblockLocalArg) (res chat1.NonblockFetchRes, err error) {
var breaks []keybase1.TLFIdentifyFailure
ctx = Context(ctx, h.G(), arg.IdentifyBehavior, &breaks, h.identNotifier)
defer h.Trace(ctx, func() error { return err }, "GetInboxNonblockLocal")()
defer func() { h.setResultRateLimit(ctx, &res) }()
defer func() { err = h.handleOfflineError(ctx, err, &res) }()
defer func() {
if res.Offline {
h.Debug(ctx, "GetInboxNonblockLocal: result obtained offline")
}
}()
defer h.suspendConvLoader(ctx)()
if err = h.assertLoggedIn(ctx); err != nil {
return res, err
}
uid := h.G().Env.GetUID()
if uid.IsNil() {
return res, libkb.LoginRequiredError{}
}
// Create localized conversation callback channel
chatUI := h.getChatUI(arg.SessionID)
localizeCb := make(chan NonblockInboxResult, 1)
// Invoke nonblocking inbox read and get remote inbox version to send back as our result
localizer := NewNonblockingLocalizer(h.G(), localizeCb, arg.MaxUnbox)
_, err = h.G().InboxSource.Read(ctx, uid.ToBytes(), localizer, true, arg.Query, arg.Pagination)
if err != nil {
// If this is a convID based query, let's go ahead and drop those onto the retrier
if arg.Query != nil && len(arg.Query.ConvIDs) > 0 {
h.Debug(ctx, "GetInboxNonblockLocal: failed to get unverified inbox, marking convIDs as failed")
for _, convID := range arg.Query.ConvIDs {
h.G().FetchRetrier.Failure(ctx, uid.ToBytes(),
NewConversationRetry(h.G(), convID, nil, InboxLoad))
}
} else {
h.Debug(ctx, "GetInboxNonblockLocal: failed to load untrusted inbox, general query")
h.G().FetchRetrier.Failure(ctx, uid.ToBytes(),
NewFullInboxRetry(h.G(), arg.Query, arg.Pagination))
}
return res, err
}
// Wait for inbox to get sent to us
var lres NonblockInboxResult
if arg.SkipUnverified {
select {
case lres = <-localizeCb:
h.Debug(ctx, "GetInboxNonblockLocal: received unverified inbox, skipping send")
case <-time.After(15 * time.Second):
return res, fmt.Errorf("timeout waiting for inbox result")
case <-ctx.Done():
return res, ctx.Err()
}
} else {
select {
case lres = <-localizeCb:
if lres.InboxRes == nil {
return res, fmt.Errorf("invalid conversation localize callback received")
}
uires, err := h.presentUnverifiedInbox(ctx, lres.InboxRes.ConvsUnverified,
lres.InboxRes.Pagination, h.G().InboxSource.IsOffline(ctx))
if err != nil {
h.Debug(ctx, "GetInboxNonblockLocal: failed to present untrusted inbox, failing: %s", err.Error())
return res, err
}
jbody, err := json.Marshal(uires)
if err != nil {
h.Debug(ctx, "GetInboxNonblockLocal: failed to JSON up unverified inbox: %s", err.Error())
return res, err
}
start := time.Now()
h.Debug(ctx, "GetInboxNonblockLocal: sending unverified inbox: num convs: %d bytes: %d",
len(lres.InboxRes.ConvsUnverified), len(jbody))
chatUI.ChatInboxUnverified(ctx, chat1.ChatInboxUnverifiedArg{
SessionID: arg.SessionID,
Inbox: string(jbody),
})
h.Debug(ctx, "GetInboxNonblockLocal: sent unverified inbox successfully: %v", time.Now().Sub(start))
case <-time.After(15 * time.Second):
return res, fmt.Errorf("timeout waiting for inbox result")
case <-ctx.Done():
return res, ctx.Err()
}
}
// Consume localize callbacks and send out to UI.
var wg sync.WaitGroup
convLocalsCh := make(chan chat1.ConversationLocal, len(lres.InboxRes.ConvsUnverified))
for convRes := range localizeCb {
wg.Add(1)
go func(convRes NonblockInboxResult) {
if convRes.Err != nil {
h.Debug(ctx, "GetInboxNonblockLocal: *** error conv: id: %s err: %s",
convRes.Conv.GetConvID(), convRes.Err.Message)
chatUI.ChatInboxFailed(ctx, chat1.ChatInboxFailedArg{
SessionID: arg.SessionID,
ConvID: convRes.Conv.GetConvID(),
Error: utils.PresentConversationErrorLocal(*convRes.Err),
})
// If we get a transient failure, add this to the retrier queue
if convRes.Err.Typ == chat1.ConversationErrorType_TRANSIENT {
h.G().FetchRetrier.Failure(ctx, uid.ToBytes(),
NewConversationRetry(h.G(), convRes.Conv.GetConvID(),
&convRes.Conv.Metadata.IdTriple.Tlfid, InboxLoad))
}
} else if convRes.ConvRes != nil {
pconv := utils.PresentConversationLocal(*convRes.ConvRes, h.G().Env.GetUsername().String())
jbody, err := json.Marshal(pconv)
if err != nil {
h.Debug(ctx, "GetInboxNonblockLocal: failed to JSON conversation, skipping: %s",
err.Error())
} else {
h.Debug(ctx, "GetInboxNonblockLocal: sending verified conv: id: %s tlf: %s bytes: %d",
convRes.Conv.GetConvID(), convRes.ConvRes.Info.TLFNameExpanded(), len(jbody))
start := time.Now()
chatUI.ChatInboxConversation(ctx, chat1.ChatInboxConversationArg{
SessionID: arg.SessionID,
Conv: string(jbody),
})
h.Debug(ctx, "GetInboxNonblockLocal: sent verified conv successfully: id: %s time: %v",
convRes.Conv.GetConvID(), time.Now().Sub(start))
}
convLocalsCh <- *convRes.ConvRes
// Send a note to the retrier that we actually loaded this guy successfully
h.G().FetchRetrier.Success(ctx, uid.ToBytes(),
NewConversationRetry(h.G(), convRes.Conv.GetConvID(),
&convRes.Conv.Metadata.IdTriple.Tlfid, InboxLoad))
}
wg.Done()
}(convRes)
}
// Write metadata to the inbox cache
var convLocals []chat1.ConversationLocal
go func() {
wg.Wait()
close(convLocalsCh)
}()
for convLocal := range convLocalsCh {
convLocals = append(convLocals, convLocal)
}
if err = storage.NewInbox(h.G(), uid.ToBytes()).MergeLocalMetadata(ctx, convLocals); err != nil {
// Don't abort the operation on this kind of error
h.Debug(ctx, "GetInboxNonblockLocal: unable to write inbox local metadata: %s", err)
}
res.Offline = h.G().InboxSource.IsOffline(ctx)
res.IdentifyFailures = breaks
return res, nil
}
func (h *Server) MarkAsReadLocal(ctx context.Context, arg chat1.MarkAsReadLocalArg) (res chat1.MarkAsReadLocalRes, err error) {
var identBreaks []keybase1.TLFIdentifyFailure
ctx = Context(ctx, h.G(), keybase1.TLFIdentifyBehavior_CHAT_GUI, &identBreaks,
h.identNotifier)
defer h.Trace(ctx, func() error { return err },
fmt.Sprintf("MarkAsReadLocal(%s, %v)", arg.ConversationID, arg.MsgID))()
defer func() { h.setResultRateLimit(ctx, &res) }()
defer func() { err = h.handleOfflineError(ctx, err, &res) }()
if err = h.assertLoggedIn(ctx); err != nil {
return chat1.MarkAsReadLocalRes{}, err
}
uid := gregor1.UID(h.G().Env.GetUID().ToBytes())
// Don't send remote mark as read if we somehow get this in the background.
if h.G().AppState.State() != keybase1.AppState_FOREGROUND {
h.Debug(ctx, "MarkAsReadLocal: not marking as read, app state not foreground: %v",
h.G().AppState.State())
return chat1.MarkAsReadLocalRes{
Offline: h.G().Syncer.IsConnected(ctx),
}, nil
}
// Check local copy to see if we have this convo, and have fully read it. If so, we skip the remote call
readRes, err := storage.NewInbox(h.G(), uid).GetConversation(ctx, arg.ConversationID)
if err == nil && readRes.GetConvID().Eq(arg.ConversationID) &&
readRes.Conv.ReaderInfo.ReadMsgid == readRes.Conv.ReaderInfo.MaxMsgid {
h.Debug(ctx, "MarkAsReadLocal: conversation fully read: %s, not sending remote call",
arg.ConversationID)
return chat1.MarkAsReadLocalRes{
Offline: h.G().Syncer.IsConnected(ctx),
}, nil
}
_, err = h.remoteClient().MarkAsRead(ctx, chat1.MarkAsReadArg{
ConversationID: arg.ConversationID,
MsgID: arg.MsgID,
})
if err != nil {
return res, err
}
return chat1.MarkAsReadLocalRes{
Offline: h.G().Syncer.IsConnected(ctx),
}, nil
}
// GetInboxAndUnboxLocal implements keybase.chatLocal.getInboxAndUnboxLocal protocol.
func (h *Server) GetInboxAndUnboxLocal(ctx context.Context, arg chat1.GetInboxAndUnboxLocalArg) (res chat1.GetInboxAndUnboxLocalRes, err error) {
var identBreaks []keybase1.TLFIdentifyFailure
ctx = Context(ctx, h.G(), arg.IdentifyBehavior, &identBreaks, h.identNotifier)
defer h.Trace(ctx, func() error { return err }, "GetInboxAndUnboxLocal")()
defer func() { h.setResultRateLimit(ctx, &res) }()
defer func() { err = h.handleOfflineError(ctx, err, &res) }()
if err = h.assertLoggedIn(ctx); err != nil {
return res, err
}
uid := h.G().Env.GetUID()
if uid.IsNil() {
err = libkb.LoginRequiredError{}
return res, err
}
// Read inbox from the source
localizer := NewBlockingLocalizer(h.G())
ib, err := h.G().InboxSource.Read(ctx, uid.ToBytes(), localizer, true, arg.Query, arg.Pagination)
if err != nil {
return res, err
}
return chat1.GetInboxAndUnboxLocalRes{
Conversations: ib.Convs,
Pagination: ib.Pagination,
Offline: h.G().InboxSource.IsOffline(ctx),
IdentifyFailures: identBreaks,
}, nil
}
func (h *Server) GetInboxAndUnboxUILocal(ctx context.Context, arg chat1.GetInboxAndUnboxUILocalArg) (res chat1.GetInboxAndUnboxUILocalRes, err error) {
var identBreaks []keybase1.TLFIdentifyFailure
ctx = Context(ctx, h.G(), arg.IdentifyBehavior, &identBreaks, h.identNotifier)
defer h.Trace(ctx, func() error { return err }, "GetInboxAndUnboxUILocal")()
defer func() { h.setResultRateLimit(ctx, &res) }()
defer func() { err = h.handleOfflineError(ctx, err, &res) }()
if err = h.assertLoggedIn(ctx); err != nil {
return res, err
}
uid := h.G().Env.GetUID()
if uid.IsNil() {
err = libkb.LoginRequiredError{}
return res, err
}
// Read inbox from the source
localizer := NewBlockingLocalizer(h.G())
ib, err := h.G().InboxSource.Read(ctx, uid.ToBytes(), localizer, true, arg.Query, arg.Pagination)
if err != nil {
return res, err
}
return chat1.GetInboxAndUnboxUILocalRes{
Conversations: utils.PresentConversationLocals(ib.Convs, h.G().Env.GetUsername().String()),
Pagination: ib.Pagination,
IdentifyFailures: identBreaks,
}, nil
}
func (h *Server) GetCachedThread(ctx context.Context, arg chat1.GetCachedThreadArg) (res chat1.GetThreadLocalRes, err error) {
var identBreaks []keybase1.TLFIdentifyFailure
ctx = Context(ctx, h.G(), arg.IdentifyBehavior, &identBreaks, h.identNotifier)
defer h.Trace(ctx, func() error { return err }, "GetCachedThread")()
defer func() { h.setResultRateLimit(ctx, &res) }()
defer func() { err = h.handleOfflineError(ctx, err, &res) }()
if err = h.assertLoggedIn(ctx); err != nil {
return chat1.GetThreadLocalRes{}, err
}
// Get messages from local disk only
uid := h.G().Env.GetUID()
thread, err := h.G().ConvSource.PullLocalOnly(ctx, arg.ConversationID,
gregor1.UID(uid.ToBytes()), arg.Query, arg.Pagination, 0)
if err != nil {
return chat1.GetThreadLocalRes{}, err
}
return chat1.GetThreadLocalRes{
Thread: thread,
Offline: h.G().ConvSource.IsOffline(ctx),
IdentifyFailures: identBreaks,
}, nil
}
// GetThreadLocal implements keybase.chatLocal.getThreadLocal protocol.
func (h *Server) GetThreadLocal(ctx context.Context, arg chat1.GetThreadLocalArg) (res chat1.GetThreadLocalRes, err error) {
var identBreaks []keybase1.TLFIdentifyFailure
ctx = Context(ctx, h.G(), arg.IdentifyBehavior, &identBreaks, h.identNotifier)
defer h.Trace(ctx, func() error { return err }, "GetThreadLocal")()
defer func() { h.setResultRateLimit(ctx, &res) }()
defer func() { err = h.handleOfflineError(ctx, err, &res) }()
if err = h.assertLoggedIn(ctx); err != nil {
return chat1.GetThreadLocalRes{}, err
}
// Xlate pager control into pagination if given
if arg.Query != nil && arg.Query.MessageIDControl != nil {
arg.Pagination = utils.XlateMessageIDControlToPagination(arg.Query.MessageIDControl)
}
// Get messages from the source
uid := h.G().Env.GetUID()
thread, err := h.G().ConvSource.Pull(ctx, arg.ConversationID,
gregor1.UID(uid.ToBytes()), arg.Reason, arg.Query, arg.Pagination)
if err != nil {
return chat1.GetThreadLocalRes{}, err
}
return chat1.GetThreadLocalRes{
Thread: thread,
Offline: h.G().ConvSource.IsOffline(ctx),
IdentifyFailures: identBreaks,
}, nil
}
func (h *Server) mergeLocalRemoteThread(ctx context.Context, remoteThread, localThread *chat1.ThreadView,
mode chat1.GetThreadNonblockCbMode) (res chat1.ThreadView, err error) {
defer func() {
if err != nil || localThread == nil {
return
}
rm := make(map[chat1.MessageID]bool)
for _, m := range res.Messages {
rm[m.GetMessageID()] = true
}
// Check for any stray placeholders in the local thread we sent, and set them to some
// undisplayable type
for _, m := range localThread.Messages {
state, err := m.State()
if err != nil {
continue
}
if state == chat1.MessageUnboxedState_PLACEHOLDER && !rm[m.GetMessageID()] {
h.Debug(ctx, "mergeLocalRemoteThread: subbing in dead placeholder: msgID: %d",
m.GetMessageID())
res.Messages = append(res.Messages, chat1.NewMessageUnboxedWithPlaceholder(
chat1.MessageUnboxedPlaceholder{
MessageID: m.GetMessageID(),
Hidden: true,
},
))
}
}
sort.Sort(utils.ByMsgUnboxedMsgID(res.Messages))
}()
shouldAppend := func(oldMsg chat1.MessageUnboxed) bool {
state, err := oldMsg.State()
if err != nil {
return true
}
switch state {
case chat1.MessageUnboxedState_VALID:
return false
default:
return true
}
}
switch mode {
case chat1.GetThreadNonblockCbMode_FULL:
return *remoteThread, nil
case chat1.GetThreadNonblockCbMode_INCREMENTAL:
if localThread != nil {
lm := make(map[chat1.MessageID]chat1.MessageUnboxed)
for _, m := range localThread.Messages {
lm[m.GetMessageID()] = m
}
res.Pagination = remoteThread.Pagination
for _, m := range remoteThread.Messages {
oldMsg, ok := lm[m.GetMessageID()]
if !ok || shouldAppend(oldMsg) {
res.Messages = append(res.Messages, m)
}
}
h.Debug(ctx, "mergeLocalRemoteThread: incremental cb mode: orig: %d post: %d",
len(remoteThread.Messages), len(res.Messages))
return res, nil
}
return *remoteThread, nil
}
return res, errors.New("unknown get thread cb mode")
}
func (h *Server) applyPagerModeIncoming(ctx context.Context, convID chat1.ConversationID,
pagination *chat1.Pagination, pgmode chat1.GetThreadNonblockPgMode) (res *chat1.Pagination) {
defer func() {
h.Debug(ctx, "applyPagerModeIncoming: mode: %v convID: %s xform: %s -> %s", pgmode, convID,
pagination, res)
}()
switch pgmode {
case chat1.GetThreadNonblockPgMode_DEFAULT:
return pagination
case chat1.GetThreadNonblockPgMode_SERVER:
if pagination == nil {
return nil
}
if len(pagination.Next) > 0 {
return &chat1.Pagination{
Num: pagination.Num,
Next: h.convPageStatus[convID.String()].Next,
}
} else if len(pagination.Previous) > 0 {
return &chat1.Pagination{
Num: pagination.Num,
Previous: h.convPageStatus[convID.String()].Previous,
}
} else {
return pagination
}
}
return pagination
}
func (h *Server) applyPagerModeOutgoing(ctx context.Context, convID chat1.ConversationID,
pagination *chat1.Pagination, incoming *chat1.Pagination, pgmode chat1.GetThreadNonblockPgMode) {
switch pgmode {
case chat1.GetThreadNonblockPgMode_DEFAULT:
case chat1.GetThreadNonblockPgMode_SERVER:
if pagination == nil {
return
}
if incoming.FirstPage() {
h.Debug(ctx, "applyPagerModeOutgoing: resetting pagination: convID: %s p: %s", convID, pagination)
h.convPageStatus[convID.String()] = *pagination
} else {
oldStored := h.convPageStatus[convID.String()]
if len(incoming.Next) > 0 {
oldStored.Next = pagination.Next
h.Debug(ctx, "applyPagerModeOutgoing: setting next pagination: convID: %s p: %s", convID,
pagination)
} else if len(incoming.Previous) > 0 {
h.Debug(ctx, "applyPagerModeOutgoing: setting prev pagination: convID: %s p: %s", convID,
pagination)
oldStored.Previous = pagination.Previous
}
h.convPageStatus[convID.String()] = oldStored
}
}
}
func (h *Server) dispatchOldPagesJob(ctx context.Context, convID chat1.ConversationID, uid gregor1.UID,
pagination *chat1.Pagination, resultPagination *chat1.Pagination) {
// Fire off pageback background jobs if we fetched the first page
if pagination.FirstPage() && resultPagination != nil && !resultPagination.Last {
p := &chat1.Pagination{
Num: 50,
Next: resultPagination.Next,
}
h.Debug(ctx, "dispatchOldPagesJob: queuing %s because of first page fetch: p: %s", convID, p)
if err := h.G().ConvLoader.Queue(ctx, types.NewConvLoaderJob(convID, p, types.ConvLoaderPriorityLow,
newConvLoaderPagebackHook(h.G(), 0, 5))); err != nil {
h.Debug(ctx, "dispatchOldPagesJob: failed to queue conversation load: %s", err)
}
}
}
func (h *Server) GetThreadNonblock(ctx context.Context, arg chat1.GetThreadNonblockArg) (res chat1.NonblockFetchRes, fullErr error) {
var pagination, resultPagination *chat1.Pagination
var identBreaks []keybase1.TLFIdentifyFailure
ctx = Context(ctx, h.G(), arg.IdentifyBehavior, &identBreaks, h.identNotifier)
uid := gregor1.UID(h.G().Env.GetUID().ToBytes())
defer h.Trace(ctx, func() error { return fullErr },
fmt.Sprintf("GetThreadNonblock(%s,%v,%v)", arg.ConversationID, arg.CbMode, arg.Reason))()
defer func() { h.setResultRateLimit(ctx, &res) }()
defer func() {
fullErr = h.handleOfflineError(ctx, fullErr, &res)
// Detect any problem loading the thread, and queue it up in the retrier if there is a problem.
// Otherwise, send notice that we successfully loaded the conversation.
if res.Offline || fullErr != nil {
h.G().FetchRetrier.Failure(ctx, uid,
NewConversationRetry(h.G(), arg.ConversationID, nil, ThreadLoad))
} else {
h.G().FetchRetrier.Success(ctx, uid,
NewConversationRetry(h.G(), arg.ConversationID, nil, ThreadLoad))
// Load old pages of this conversation on success
h.dispatchOldPagesJob(ctx, arg.ConversationID, uid, pagination, resultPagination)
}
}()
defer h.suspendConvLoader(ctx)()
// Lock conversation while this is running
if err := h.G().ConvSource.AcquireConversationLock(ctx, uid, arg.ConversationID); err != nil {
return res, err
}
defer h.G().ConvSource.ReleaseConversationLock(ctx, uid, arg.ConversationID)
h.Debug(ctx, "GetThreadNonblock: conversation lock obtained")
if err := h.assertLoggedIn(ctx); err != nil {
return res, err
}
// If this is from a push or foreground, set us into the foreground
switch arg.Reason {
case chat1.GetThreadReason_PUSH, chat1.GetThreadReason_FOREGROUND:
// Also if we get here and we claim to not be in the foreground yet, then hit disconnect
// to reset any delay checks or timers
switch h.G().AppState.State() {
case keybase1.AppState_FOREGROUND, keybase1.AppState_BACKGROUNDACTIVE:
default:
h.G().Syncer.Disconnected(ctx)
}
h.G().AppState.Update(keybase1.AppState_FOREGROUND)
}
// Set last select conversation on syncer
h.G().Syncer.SelectConversation(ctx, arg.ConversationID)
// Decode presentation form pagination
var err error
if pagination, err = utils.DecodePagination(arg.Pagination); err != nil {
return res, err
}
// Xlate pager control into pagination if given
if arg.Query != nil && arg.Query.MessageIDControl != nil {
pagination = utils.XlateMessageIDControlToPagination(arg.Query.MessageIDControl)
}
// Apply any pager mode transformations
pagination = h.applyPagerModeIncoming(ctx, arg.ConversationID, pagination, arg.Pgmode)
// Grab local copy first
chatUI := h.getChatUI(arg.SessionID)
// Race the full operation versus the local one, so we don't lose anytime grabbing the local
// version if they are roughly as fast. However, the full operation has preference, so if it does
// win the race we don't send anything up from the local operation.
var localSentThread *chat1.ThreadView
var uilock sync.Mutex
var wg sync.WaitGroup
bctx, cancel := context.WithCancel(ctx)
wg.Add(1)
go func() {
defer wg.Done()
// Get local copy of the thread, abort the call if we have sent the full copy
var resThread *chat1.ThreadView
var localThread chat1.ThreadView
ch := make(chan error, 1)
go func() {
var err error
if h.cachedThreadDelay != nil {
h.clock.Sleep(*h.cachedThreadDelay)
}
localThread, err = h.G().ConvSource.PullLocalOnly(bctx, arg.ConversationID,
uid, arg.Query, pagination, 10)
ch <- err
}()
select {
case err := <-ch:
if err != nil {
h.Debug(ctx, "GetThreadNonblock: error running PullLocalOnly (sending miss): %s",
err.Error())
} else {
resThread = &localThread
}
case <-bctx.Done():
h.Debug(ctx, "GetThreadNonblock: context canceled before PullLocalOnly returned")
return
}
uilock.Lock()
defer uilock.Unlock()
// Check this again, since we might have waited on the lock while full sent
select {
case <-bctx.Done():
resThread = nil
h.Debug(ctx, "GetThreadNonblock: context canceled before local copy sent")
return
default:
}
var pthread *string
if resThread != nil {
h.Debug(ctx, "GetThreadNonblock: sending cached response: messages: %d pager: %s",
len(resThread.Messages), resThread.Pagination)
var jsonPt []byte
var err error
localSentThread = resThread
pt := utils.PresentThreadView(ctx, h.G(), uid, *resThread, arg.ConversationID)
if jsonPt, err = json.Marshal(pt); err != nil {
h.Debug(ctx, "GetThreadNonblock: failed to JSON cached response: %s", err)
return
}
sJSONPt := string(jsonPt)
pthread = &sJSONPt
h.applyPagerModeOutgoing(bctx, arg.ConversationID, resThread.Pagination, pagination, arg.Pgmode)
} else {
h.Debug(ctx, "GetThreadNonblock: sending nil cached response")
}
start := time.Now()
chatUI.ChatThreadCached(bctx, chat1.ChatThreadCachedArg{
SessionID: arg.SessionID,
Thread: pthread,
})
h.Debug(ctx, "GetThreadNonblock: cached response send time: %v", time.Since(start))
}()
wg.Add(1)
go func() {
defer wg.Done()
// Run the full Pull operation, and redo pagination
if h.remoteThreadDelay != nil {
h.clock.Sleep(*h.remoteThreadDelay)
}
var remoteThread chat1.ThreadView
remoteThread, fullErr = h.G().ConvSource.Pull(bctx, arg.ConversationID,
uid, arg.Reason, arg.Query, pagination)
if fullErr != nil {
h.Debug(ctx, "GetThreadNonblock: error running Pull, returning error: %s", fullErr.Error())
return
}
// Acquire lock and send up actual response
uilock.Lock()
defer uilock.Unlock()
var rthread chat1.ThreadView
if rthread, fullErr =
h.mergeLocalRemoteThread(ctx, &remoteThread, localSentThread, arg.CbMode); fullErr != nil {
return
}
h.Debug(ctx, "GetThreadNonblock: sending full response: messages: %d pager: %s",
len(rthread.Messages), rthread.Pagination)
uires := utils.PresentThreadView(bctx, h.G(), uid, rthread, arg.ConversationID)
var jsonUIRes []byte
if jsonUIRes, fullErr = json.Marshal(uires); fullErr != nil {
h.Debug(ctx, "GetThreadNonblock: failed to JSON full result: %s", fullErr)
return
}
resultPagination = rthread.Pagination
h.applyPagerModeOutgoing(bctx, arg.ConversationID, rthread.Pagination, pagination, arg.Pgmode)
start := time.Now()
chatUI.ChatThreadFull(bctx, chat1.ChatThreadFullArg{
SessionID: arg.SessionID,
Thread: string(jsonUIRes),
})
h.Debug(ctx, "GetThreadNonblock: full response send time: %v", time.Since(start))
// This means we transmitted with success, so cancel local thread
cancel()
}()
wg.Wait()
// Clean up context
cancel()
res.Offline = h.G().ConvSource.IsOffline(ctx)
return res, fullErr
}
// NewConversationLocal implements keybase.chatLocal.newConversationLocal protocol.
// Create a new conversation. Or in the case of CHAT, create-or-get a conversation.
func (h *Server) NewConversationLocal(ctx context.Context, arg chat1.NewConversationLocalArg) (res chat1.NewConversationLocalRes, err error) {
var identBreaks []keybase1.TLFIdentifyFailure
ctx = Context(ctx, h.G(), arg.IdentifyBehavior, &identBreaks, h.identNotifier)
defer h.Trace(ctx, func() error { return err },
fmt.Sprintf("NewConversationLocal(%s|%v)", arg.TlfName, arg.MembersType))()
defer func() { h.setResultRateLimit(ctx, &res) }()
if err := h.assertLoggedIn(ctx); err != nil {
return chat1.NewConversationLocalRes{}, err
}
uid := gregor1.UID(h.G().Env.GetUID().ToBytes())
conv, err := NewConversation(ctx, h.G(), uid, arg.TlfName, arg.TopicName,
arg.TopicType, arg.MembersType, arg.TlfVisibility, h.remoteClient)
if err != nil {
return res, err
}
res.Conv = conv
res.IdentifyFailures = identBreaks
return res, nil
}
func (h *Server) GetInboxSummaryForCLILocal(ctx context.Context, arg chat1.GetInboxSummaryForCLILocalQuery) (res chat1.GetInboxSummaryForCLILocalRes, err error) {
var identBreaks []keybase1.TLFIdentifyFailure
ctx = Context(ctx, h.G(), keybase1.TLFIdentifyBehavior_CHAT_CLI, &identBreaks,
h.identNotifier)
defer h.Trace(ctx, func() error { return err }, "GetInboxSummaryForCLILocal")()
defer func() { h.setResultRateLimit(ctx, &res) }()
defer func() { err = h.handleOfflineError(ctx, err, &res) }()
if err = h.assertLoggedIn(ctx); err != nil {
return chat1.GetInboxSummaryForCLILocalRes{}, err
}
var after time.Time
if len(arg.After) > 0 {
after, err = utils.ParseTimeFromRFC3339OrDurationFromPast(h.G(), arg.After)
if err != nil {
return chat1.GetInboxSummaryForCLILocalRes{}, fmt.Errorf("parsing time or duration (%s) error: %s", arg.After, err)
}
}
var before time.Time
if len(arg.Before) > 0 {
before, err = utils.ParseTimeFromRFC3339OrDurationFromPast(h.G(), arg.Before)
if err != nil {
return chat1.GetInboxSummaryForCLILocalRes{}, fmt.Errorf("parsing time or duration (%s) error: %s", arg.Before, err)
}
}
var queryBase chat1.GetInboxLocalQuery
queryBase.ComputeActiveList = true
queryBase.OneChatTypePerTLF = new(bool)
*queryBase.OneChatTypePerTLF = true
if !after.IsZero() {
gafter := gregor1.ToTime(after)
queryBase.After = &gafter
}
if !before.IsZero() {
gbefore := gregor1.ToTime(before)
queryBase.Before = &gbefore
}
if arg.TopicType != chat1.TopicType_NONE {
queryBase.TopicType = &arg.TopicType
}
if arg.Visibility != keybase1.TLFVisibility_ANY {
queryBase.TlfVisibility = &arg.Visibility
}
queryBase.Status = arg.Status
var gires chat1.GetInboxAndUnboxLocalRes
if arg.UnreadFirst {
if arg.UnreadFirstLimit.AtMost <= 0 {
arg.UnreadFirstLimit.AtMost = int(^uint(0) >> 1) // maximum int
}
if arg.UnreadFirstLimit.AtMost < arg.UnreadFirstLimit.AtLeast {
arg.UnreadFirstLimit.AtMost = arg.UnreadFirstLimit.AtLeast
}
query := queryBase
query.UnreadOnly, query.ReadOnly = true, false
if gires, err = h.GetInboxAndUnboxLocal(ctx, chat1.GetInboxAndUnboxLocalArg{
Pagination: &chat1.Pagination{Num: arg.UnreadFirstLimit.AtMost},
Query: &query,
IdentifyBehavior: keybase1.TLFIdentifyBehavior_CHAT_CLI,
}); err != nil {
return chat1.GetInboxSummaryForCLILocalRes{}, err
}
res.Conversations = gires.Conversations
more := utils.Collar(
arg.UnreadFirstLimit.AtLeast-len(res.Conversations),
arg.UnreadFirstLimit.NumRead,
arg.UnreadFirstLimit.AtMost-len(res.Conversations),
)
if more > 0 {
query := queryBase
query.UnreadOnly, query.ReadOnly = false, true
if gires, err = h.GetInboxAndUnboxLocal(ctx, chat1.GetInboxAndUnboxLocalArg{
Pagination: &chat1.Pagination{Num: more},
Query: &query,
}); err != nil {
return chat1.GetInboxSummaryForCLILocalRes{}, err
}
res.Conversations = append(res.Conversations, gires.Conversations...)
}
} else {
if arg.ActivitySortedLimit <= 0 {
arg.ActivitySortedLimit = int(^uint(0) >> 1) // maximum int
}
query := queryBase
query.UnreadOnly, query.ReadOnly = false, false
if gires, err = h.GetInboxAndUnboxLocal(ctx, chat1.GetInboxAndUnboxLocalArg{
Pagination: &chat1.Pagination{Num: arg.ActivitySortedLimit},
Query: &query,
IdentifyBehavior: keybase1.TLFIdentifyBehavior_CHAT_CLI,
}); err != nil {
return chat1.GetInboxSummaryForCLILocalRes{}, err
}
res.Conversations = gires.Conversations
}
res.Offline = gires.Offline
return res, nil
}
func (h *Server) GetConversationForCLILocal(ctx context.Context, arg chat1.GetConversationForCLILocalQuery) (res chat1.GetConversationForCLILocalRes, err error) {
var identBreaks []keybase1.TLFIdentifyFailure
ctx = Context(ctx, h.G(), keybase1.TLFIdentifyBehavior_CHAT_CLI, &identBreaks,
h.identNotifier)
defer h.Trace(ctx, func() error { return err }, "GetConversationForCLILocal")()
defer func() { h.setResultRateLimit(ctx, &res) }()
defer func() { err = h.handleOfflineError(ctx, err, &res) }()
if err := h.assertLoggedIn(ctx); err != nil {
return chat1.GetConversationForCLILocalRes{}, err
}
if arg.Limit.AtMost <= 0 {
arg.Limit.AtMost = int(^uint(0) >> 1) // maximum int
}
if arg.Limit.AtMost < arg.Limit.AtLeast {
arg.Limit.AtMost = arg.Limit.AtLeast
}
convLocal := arg.Conv
var since time.Time
if arg.Since != nil {
since, err = utils.ParseTimeFromRFC3339OrDurationFromPast(h.G(), *arg.Since)
if err != nil {
return chat1.GetConversationForCLILocalRes{}, fmt.Errorf("parsing time or duration (%s) error: %s", *arg.Since, since)
}
}
query := chat1.GetThreadQuery{
MarkAsRead: arg.MarkAsRead,
MessageTypes: arg.MessageTypes,
}
if !since.IsZero() {
gsince := gregor1.ToTime(since)
query.After = &gsince
}
tv, err := h.GetThreadLocal(ctx, chat1.GetThreadLocalArg{
ConversationID: convLocal.Info.Id,
Query: &query,
IdentifyBehavior: keybase1.TLFIdentifyBehavior_CHAT_CLI,
})
if err != nil {
return chat1.GetConversationForCLILocalRes{}, err
}
// apply message count limits
var messages []chat1.MessageUnboxed
for _, m := range tv.Thread.Messages {
messages = append(messages, m)
arg.Limit.AtMost--
arg.Limit.AtLeast--
if m.GetMessageID() <= convLocal.ReaderInfo.ReadMsgid {
arg.Limit.NumRead--
}
if arg.Limit.AtMost <= 0 ||
(arg.Limit.NumRead <= 0 && arg.Limit.AtLeast <= 0) {
break
}
}
return chat1.GetConversationForCLILocalRes{
Conversation: convLocal,
Messages: messages,
Offline: tv.Offline,
}, nil
}
func (h *Server) GetMessagesLocal(ctx context.Context, arg chat1.GetMessagesLocalArg) (res chat1.GetMessagesLocalRes, err error) {
var identBreaks []keybase1.TLFIdentifyFailure