-
Notifications
You must be signed in to change notification settings - Fork 52
/
msc2716_test.go
1213 lines (1022 loc) · 44.2 KB
/
msc2716_test.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
// +build msc2716
// This file contains tests for incrementally importing history to an existing room,
// a currently experimental feature defined by MSC2716, which you can read here:
// https://github.com/matrix-org/matrix-doc/pull/2716
package tests
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"testing"
"time"
"github.com/tidwall/gjson"
"github.com/matrix-org/complement/internal/b"
"github.com/matrix-org/complement/internal/client"
"github.com/matrix-org/complement/internal/match"
"github.com/matrix-org/complement/internal/must"
)
type event struct {
Type string
Sender string
OriginServerTS uint64
StateKey *string
PrevEvents []string
Content map[string]interface{}
}
// This is configurable because it can be nice to change it to `time.Second` while
// checking out the test result in a Synapse instance
const timeBetweenMessages = time.Millisecond
var (
insertionEventType = "org.matrix.msc2716.insertion"
batchEventType = "org.matrix.msc2716.batch"
markerEventType = "org.matrix.msc2716.marker"
historicalContentField = "org.matrix.msc2716.historical"
nextBatchIDContentField = "org.matrix.msc2716.next_batch_id"
markerInsertionContentField = "org.matrix.msc2716.marker.insertion"
)
var createPublicRoomOpts = map[string]interface{}{
"preset": "public_chat",
"name": "the hangout spot",
"room_version": "org.matrix.msc2716v3",
}
var createPrivateRoomOpts = map[string]interface{}{
"preset": "private_chat",
"name": "the hangout spot",
"room_version": "org.matrix.msc2716v3",
}
func TestImportHistoricalMessages(t *testing.T) {
deployment := Deploy(t, b.BlueprintHSWithApplicationService)
defer deployment.Destroy(t)
// Create the application service bridge user that is able to import historical messages
asUserID := "@the-bridge-user:hs1"
as := deployment.Client(t, "hs1", asUserID)
// Create the normal user which will send messages in the room
userID := "@alice:hs1"
alice := deployment.Client(t, "hs1", userID)
// Create the federated user which will fetch the messages from a remote homeserver
remoteUserID := "@charlie:hs2"
remoteCharlie := deployment.Client(t, "hs2", remoteUserID)
virtualUserLocalpart := "maria"
virtualUserID := fmt.Sprintf("@%s:hs1", virtualUserLocalpart)
// Register and join the virtual user
ensureVirtualUserRegistered(t, as, virtualUserLocalpart)
t.Run("parallel", func(t *testing.T) {
// Test that the historical message events we import between A and B
// come back in the correct order from /messages.
//
// Final timeline output: ( [n] = historical batch )
// (oldest) A, B, [insertion, c, d, e, batch] [insertion, f, g, h, batch, insertion], I, J (newest)
// historical batch 1 historical batch 0
t.Run("Historical events resolve with proper state in correct order", func(t *testing.T) {
t.Parallel()
roomID := as.CreateRoom(t, createPublicRoomOpts)
alice.JoinRoom(t, roomID, nil)
// Create some normal messages in the timeline. We're creating them in
// two batches so we can create some time in between where we are going
// to import.
//
// Create the first batch including the "live" event we are going to
// import our historical events next to.
eventIDsBefore := createMessagesInRoom(t, alice, roomID, 2)
eventIdBefore := eventIDsBefore[len(eventIDsBefore)-1]
timeAfterEventBefore := time.Now()
// wait X number of ms to ensure that the timestamp changes enough for
// each of the historical messages we try to import later
numHistoricalMessages := 6
time.Sleep(time.Duration(numHistoricalMessages) * timeBetweenMessages)
// Create the second batch of events.
// This will also fill up the buffer so we have to scrollback to the
// inserted history later.
eventIDsAfter := createMessagesInRoom(t, alice, roomID, 2)
// Insert the most recent batch of historical messages
insertTime0 := timeAfterEventBefore.Add(timeBetweenMessages * 3)
batchSendRes := batchSendHistoricalMessages(
t,
as,
roomID,
eventIdBefore,
"",
createJoinStateEventsForBatchSendRequest([]string{virtualUserID}, insertTime0),
createMessageEventsForBatchSendRequest([]string{virtualUserID}, insertTime0, 3),
// Status
200,
)
batchSendResBody0 := client.ParseJSON(t, batchSendRes)
insertionEventID0 := client.GetJSONFieldStr(t, batchSendResBody0, "insertion_event_id")
historicalEventIDs0 := client.GetJSONFieldStringArray(t, batchSendResBody0, "event_ids")
batchEventID0 := client.GetJSONFieldStr(t, batchSendResBody0, "batch_event_id")
baseInsertionEventID0 := client.GetJSONFieldStr(t, batchSendResBody0, "base_insertion_event_id")
nextBatchID0 := client.GetJSONFieldStr(t, batchSendResBody0, "next_batch_id")
// Insert another older batch of historical messages from the same user.
// Make sure the meta data and joins still work on the subsequent batch
insertTime1 := timeAfterEventBefore
batchSendRes1 := batchSendHistoricalMessages(
t,
as,
roomID,
eventIdBefore,
nextBatchID0,
createJoinStateEventsForBatchSendRequest([]string{virtualUserID}, insertTime1),
createMessageEventsForBatchSendRequest([]string{virtualUserID}, insertTime1, 3),
// Status
200,
)
batchSendResBody1 := client.ParseJSON(t, batchSendRes1)
insertionEventID1 := client.GetJSONFieldStr(t, batchSendResBody1, "insertion_event_id")
historicalEventIDs1 := client.GetJSONFieldStringArray(t, batchSendResBody1, "event_ids")
batchEventID1 := client.GetJSONFieldStr(t, batchSendResBody1, "batch_event_id")
var expectedEventIDOrder []string
expectedEventIDOrder = append(expectedEventIDOrder, eventIDsBefore...)
expectedEventIDOrder = append(expectedEventIDOrder, insertionEventID1)
expectedEventIDOrder = append(expectedEventIDOrder, historicalEventIDs1...)
expectedEventIDOrder = append(expectedEventIDOrder, batchEventID1)
expectedEventIDOrder = append(expectedEventIDOrder, insertionEventID0)
expectedEventIDOrder = append(expectedEventIDOrder, historicalEventIDs0...)
expectedEventIDOrder = append(expectedEventIDOrder, batchEventID0)
expectedEventIDOrder = append(expectedEventIDOrder, baseInsertionEventID0)
expectedEventIDOrder = append(expectedEventIDOrder, eventIDsAfter...)
// Order events from newest to oldest
expectedEventIDOrder = reversed(expectedEventIDOrder)
// (oldest) A, B, [insertion, c, d, e, batch] [insertion, f, g, h, batch, insertion], I, J (newest)
// historical batch 1 historical batch 0
if len(expectedEventIDOrder) != 15 {
t.Fatalf("Expected eventID list should be length 15 but saw %d: %s", len(expectedEventIDOrder), expectedEventIDOrder)
}
messagesRes := alice.MustDoFunc(t, "GET", []string{"_matrix", "client", "r0", "rooms", roomID, "messages"}, client.WithContentType("application/json"), client.WithQueries(url.Values{
"dir": []string{"b"},
"limit": []string{"100"},
}))
messsageResBody := client.ParseJSON(t, messagesRes)
eventDebugStringsFromResponse := getRelevantEventDebugStringsFromMessagesResponse(t, messsageResBody)
// Since the original body can only be read once, create a new one from the body bytes we just read
messagesRes.Body = ioutil.NopCloser(bytes.NewBuffer(messsageResBody))
// Copy the array by slice so we can modify it as we iterate in the foreach loop.
// We save the full untouched `expectedEventIDOrder` for use in the log messages
workingExpectedEventIDOrder := expectedEventIDOrder
must.MatchResponse(t, messagesRes, match.HTTPResponse{
JSON: []match.JSON{
match.JSONArrayEach("chunk", func(r gjson.Result) error {
// Find all events in order
if isRelevantEvent(r) {
// Pop the next message off the expected list
nextEventIdInOrder := workingExpectedEventIDOrder[0]
workingExpectedEventIDOrder = workingExpectedEventIDOrder[1:]
if r.Get("event_id").Str != nextEventIdInOrder {
return fmt.Errorf("Next event found was %s but expected %s\nActualEvents (%d): %v\nExpectedEvents (%d): %v", r.Get("event_id").Str, nextEventIdInOrder, len(eventDebugStringsFromResponse), eventDebugStringsFromResponse, len(expectedEventIDOrder), expectedEventIDOrder)
}
}
return nil
}),
},
})
if len(workingExpectedEventIDOrder) != 0 {
t.Fatalf("Expected all events to be matched in message response but there were some left-over events: %s", workingExpectedEventIDOrder)
}
})
t.Run("Historical events from multiple users in the same batch", func(t *testing.T) {
t.Parallel()
roomID := as.CreateRoom(t, createPublicRoomOpts)
alice.JoinRoom(t, roomID, nil)
// Create the "live" event we are going to insert our historical events next to
eventIDsBefore := createMessagesInRoom(t, alice, roomID, 1)
eventIdBefore := eventIDsBefore[0]
timeAfterEventBefore := time.Now()
// Register and join the other virtual users
virtualUserID2 := "@ricky:hs1"
ensureVirtualUserRegistered(t, as, "ricky")
virtualUserID3 := "@carol:hs1"
ensureVirtualUserRegistered(t, as, "carol")
virtualUserList := []string{virtualUserID, virtualUserID2, virtualUserID3}
// Import a historical event
batchSendRes := batchSendHistoricalMessages(
t,
as,
roomID,
eventIdBefore,
"",
createJoinStateEventsForBatchSendRequest(virtualUserList, timeAfterEventBefore),
createMessageEventsForBatchSendRequest(virtualUserList, timeAfterEventBefore, 3),
// Status
200,
)
batchSendResBody := client.ParseJSON(t, batchSendRes)
historicalEventIDs := client.GetJSONFieldStringArray(t, batchSendResBody, "event_ids")
messagesRes := alice.MustDoFunc(t, "GET", []string{"_matrix", "client", "r0", "rooms", roomID, "messages"}, client.WithContentType("application/json"), client.WithQueries(url.Values{
"dir": []string{"b"},
"limit": []string{"100"},
}))
must.MatchResponse(t, messagesRes, match.HTTPResponse{
JSON: []match.JSON{
match.JSONCheckOffAllowUnwanted("chunk", makeInterfaceSlice(historicalEventIDs), func(r gjson.Result) interface{} {
return r.Get("event_id").Str
}, nil),
},
})
})
t.Run("Historical events from /batch_send do not come down in an incremental sync", func(t *testing.T) {
t.Parallel()
roomID := as.CreateRoom(t, createPublicRoomOpts)
alice.JoinRoom(t, roomID, nil)
// Create the "live" event we are going to insert our historical events next to
eventIDsBefore := createMessagesInRoom(t, alice, roomID, 1)
eventIdBefore := eventIDsBefore[0]
timeAfterEventBefore := time.Now()
// Create some "live" events to saturate and fill up the /sync response
createMessagesInRoom(t, alice, roomID, 5)
// Import a historical event
batchSendRes := batchSendHistoricalMessages(
t,
as,
roomID,
eventIdBefore,
"",
createJoinStateEventsForBatchSendRequest([]string{virtualUserID}, timeAfterEventBefore),
createMessageEventsForBatchSendRequest([]string{virtualUserID}, timeAfterEventBefore, 1),
// Status
200,
)
batchSendResBody := client.ParseJSON(t, batchSendRes)
historicalEventIDs := client.GetJSONFieldStringArray(t, batchSendResBody, "event_ids")
historicalEventId := historicalEventIDs[0]
// This is just a dummy event we search for after the historicalEventId
eventIDsAfterHistoricalImport := createMessagesInRoom(t, alice, roomID, 1)
eventIDAfterHistoricalImport := eventIDsAfterHistoricalImport[0]
// Sync until we find the eventIDAfterHistoricalImport.
// If we're able to see the eventIDAfterHistoricalImport that occurs after
// the historicalEventId without seeing eventIDAfterHistoricalImport in
// between, we're probably safe to assume it won't sync
alice.SyncUntil(t, "", `{ "room": { "timeline": { "limit": 3 } } }`, "rooms.join."+client.GjsonEscape(roomID)+".timeline.events", func(r gjson.Result) bool {
if r.Get("event_id").Str == historicalEventId {
t.Fatalf("We should not see the %s historical event in /sync response but it was present", historicalEventId)
}
return r.Get("event_id").Str == eventIDAfterHistoricalImport
})
})
t.Run("Batch send endpoint only returns state events that we passed in via state_events_at_start", func(t *testing.T) {
t.Parallel()
roomID := as.CreateRoom(t, createPublicRoomOpts)
alice.JoinRoom(t, roomID, nil)
// Create the "live" event we are going to import our historical events next to
eventIDsBefore := createMessagesInRoom(t, alice, roomID, 1)
eventIdBefore := eventIDsBefore[0]
timeAfterEventBefore := time.Now()
// Import a historical event
batchSendRes := batchSendHistoricalMessages(
t,
as,
roomID,
eventIdBefore,
"",
createJoinStateEventsForBatchSendRequest([]string{virtualUserID}, timeAfterEventBefore),
createMessageEventsForBatchSendRequest([]string{virtualUserID}, timeAfterEventBefore, 1),
// Status
200,
)
batchSendResBody := client.ParseJSON(t, batchSendRes)
stateEventIDs := client.GetJSONFieldStringArray(t, batchSendResBody, "state_event_ids")
// We only expect 1 state event to be returned because we only passed in 1
// event into `?state_events_at_start`
if len(stateEventIDs) != 1 {
t.Fatalf("Expected only 1 state event to be returned but received %d: %v", len(stateEventIDs), stateEventIDs)
}
})
t.Run("Unrecognised prev_event ID will throw an error", func(t *testing.T) {
t.Parallel()
roomID := as.CreateRoom(t, createPublicRoomOpts)
insertTime := time.Now()
batchSendHistoricalMessages(
t,
as,
roomID,
"$some-non-existant-event-id",
"",
createJoinStateEventsForBatchSendRequest([]string{virtualUserID}, insertTime),
createMessageEventsForBatchSendRequest([]string{virtualUserID}, insertTime, 1),
// Status
// TODO: Seems like this makes more sense as a 404
// But the current Synapse code around unknown prev events will throw ->
// `403: No create event in auth events`
403,
)
})
t.Run("Unrecognised batch_id will throw an error", func(t *testing.T) {
t.Parallel()
roomID := as.CreateRoom(t, createPublicRoomOpts)
alice.JoinRoom(t, roomID, nil)
eventIDsBefore := createMessagesInRoom(t, alice, roomID, 1)
eventIdBefore := eventIDsBefore[0]
timeAfterEventBefore := time.Now()
batchSendHistoricalMessages(
t,
as,
roomID,
eventIdBefore,
"XXX_DOES_NOT_EXIST_BATCH_ID",
createJoinStateEventsForBatchSendRequest([]string{virtualUserID}, timeAfterEventBefore),
createMessageEventsForBatchSendRequest([]string{virtualUserID}, timeAfterEventBefore, 1),
// Status
400,
)
})
t.Run("Duplicate next_batch_id on insertion event will be rejected", func(t *testing.T) {
t.Parallel()
// Alice created the room and is the room creator/admin to be able to
// send historical events.
//
// We're using Alice over the application service so we can easily use
// SendEventSynced since application services can't use /sync.
roomID := alice.CreateRoom(t, createPublicRoomOpts)
alice.SendEventSynced(t, roomID, b.Event{
Type: insertionEventType,
Content: map[string]interface{}{
nextBatchIDContentField: "same",
historicalContentField: true,
},
})
txnId := getTxnID("duplicateinsertion-txn")
res := alice.DoFunc(t, "PUT", []string{"_matrix", "client", "r0", "rooms", roomID, "send", insertionEventType, txnId}, client.WithJSONBody(t, map[string]interface{}{
nextBatchIDContentField: "same",
historicalContentField: true,
}))
// We expect the send request for the duplicate insertion event to fail
expectedStatus := 400
if res.StatusCode != expectedStatus {
t.Fatalf("Expected HTTP Status to be %d but received %d", expectedStatus, res.StatusCode)
}
})
t.Run("Normal users aren't allowed to batch send historical messages", func(t *testing.T) {
t.Parallel()
roomID := as.CreateRoom(t, createPublicRoomOpts)
alice.JoinRoom(t, roomID, nil)
eventIDsBefore := createMessagesInRoom(t, alice, roomID, 1)
eventIdBefore := eventIDsBefore[0]
timeAfterEventBefore := time.Now()
batchSendHistoricalMessages(
t,
alice,
roomID,
eventIdBefore,
"",
createJoinStateEventsForBatchSendRequest([]string{virtualUserID}, timeAfterEventBefore),
createMessageEventsForBatchSendRequest([]string{virtualUserID}, timeAfterEventBefore, 1),
// Status
// Normal user alice should not be able to batch send historical messages
403,
)
})
t.Run("TODO: Trying to send insertion event with same `next_batch_id` will reject", func(t *testing.T) {
t.Skip("Skipping until implemented")
// (room_id, next_batch_id) should be unique
})
t.Run("Should be able to batch send historical messages into private room", func(t *testing.T) {
t.Parallel()
roomID := as.CreateRoom(t, createPrivateRoomOpts)
as.InviteRoom(t, roomID, alice.UserID)
alice.JoinRoom(t, roomID, nil)
// Create the "live" event we are going to import our historical events next to
eventIDsBefore := createMessagesInRoom(t, alice, roomID, 1)
eventIdBefore := eventIDsBefore[0]
timeAfterEventBefore := time.Now()
var stateEvents []map[string]interface{}
stateEvents = append(stateEvents, createInviteStateEventsForBacthSendRequest(as.UserID, []string{virtualUserID}, timeAfterEventBefore)...)
stateEvents = append(stateEvents, createJoinStateEventsForBatchSendRequest([]string{virtualUserID}, timeAfterEventBefore)...)
// Import a historical event
batchSendRes := batchSendHistoricalMessages(
t,
as,
roomID,
eventIdBefore,
"",
stateEvents,
createMessageEventsForBatchSendRequest([]string{virtualUserID}, timeAfterEventBefore, 3),
// Status
200,
)
batchSendResBody := client.ParseJSON(t, batchSendRes)
historicalEventIDs := client.GetJSONFieldStringArray(t, batchSendResBody, "event_ids")
messagesRes := alice.MustDoFunc(t, "GET", []string{"_matrix", "client", "r0", "rooms", roomID, "messages"}, client.WithContentType("application/json"), client.WithQueries(url.Values{
"dir": []string{"b"},
"limit": []string{"100"},
}))
must.MatchResponse(t, messagesRes, match.HTTPResponse{
JSON: []match.JSON{
match.JSONCheckOffAllowUnwanted("chunk", makeInterfaceSlice(historicalEventIDs), func(r gjson.Result) interface{} {
return r.Get("event_id").Str
}, nil),
},
})
})
t.Run("TODO: Test if historical avatar/display name set back in time are picked up on historical messages", func(t *testing.T) {
t.Skip("Skipping until implemented")
// TODO: Try adding avatar and displayName and see if historical messages get this info
})
t.Run("TODO: What happens when you point multiple batches at the same insertion event?", func(t *testing.T) {
t.Skip("Skipping until implemented")
})
t.Run("Historical messages are visible when joining on federated server - auto-generated base insertion event", func(t *testing.T) {
t.Parallel()
roomID := as.CreateRoom(t, createPublicRoomOpts)
alice.JoinRoom(t, roomID, nil)
eventIDsBefore := createMessagesInRoom(t, alice, roomID, 1)
eventIdBefore := eventIDsBefore[0]
timeAfterEventBefore := time.Now()
// eventIDsAfter
createMessagesInRoom(t, alice, roomID, 3)
batchSendRes := batchSendHistoricalMessages(
t,
as,
roomID,
eventIdBefore,
"",
createJoinStateEventsForBatchSendRequest([]string{virtualUserID}, timeAfterEventBefore),
createMessageEventsForBatchSendRequest([]string{virtualUserID}, timeAfterEventBefore, 2),
// Status
200,
)
batchSendResBody := client.ParseJSON(t, batchSendRes)
historicalEventIDs := client.GetJSONFieldStringArray(t, batchSendResBody, "event_ids")
// Join the room from a remote homeserver after the historical messages were sent
remoteCharlie.JoinRoom(t, roomID, []string{"hs1"})
// Make sure all of the events have been backfilled
fetchUntilMessagesResponseHas(t, remoteCharlie, roomID, func(ev gjson.Result) bool {
if ev.Get("event_id").Str == eventIdBefore {
return true
}
return false
})
messagesRes := remoteCharlie.MustDoFunc(t, "GET", []string{"_matrix", "client", "r0", "rooms", roomID, "messages"}, client.WithContentType("application/json"), client.WithQueries(url.Values{
"dir": []string{"b"},
"limit": []string{"100"},
}))
must.MatchResponse(t, messagesRes, match.HTTPResponse{
JSON: []match.JSON{
match.JSONCheckOffAllowUnwanted("chunk", makeInterfaceSlice(historicalEventIDs), func(r gjson.Result) interface{} {
return r.Get("event_id").Str
}, nil),
},
})
})
t.Run("Historical messages are visible when joining on federated server - pre-made insertion event", func(t *testing.T) {
t.Parallel()
roomID := as.CreateRoom(t, createPublicRoomOpts)
alice.JoinRoom(t, roomID, nil)
eventIDsBefore := createMessagesInRoom(t, alice, roomID, 1)
eventIdBefore := eventIDsBefore[0]
timeAfterEventBefore := time.Now()
// Create insertion event in the normal DAG
batchID := "mynextBatchID123"
insertionEvent := b.Event{
Type: insertionEventType,
Content: map[string]interface{}{
nextBatchIDContentField: batchID,
historicalContentField: true,
},
}
// We can't use as.SendEventSynced(...) because application services can't use the /sync API
txnId := getTxnID("sendInsertionAndEnsureBackfilled-txn")
insertionSendRes := as.MustDoFunc(t, "PUT", []string{"_matrix", "client", "r0", "rooms", roomID, "send", insertionEvent.Type, txnId}, client.WithJSONBody(t, insertionEvent.Content))
insertionSendBody := client.ParseJSON(t, insertionSendRes)
insertionEventID := client.GetJSONFieldStr(t, insertionSendBody, "event_id")
// Make sure the insertion event has reached the homeserver
alice.SyncUntilTimelineHas(t, roomID, func(ev gjson.Result) bool {
return ev.Get("event_id").Str == insertionEventID
})
// eventIDsAfter
createMessagesInRoom(t, alice, roomID, 3)
batchSendRes := batchSendHistoricalMessages(
t,
as,
roomID,
eventIdBefore,
batchID,
createJoinStateEventsForBatchSendRequest([]string{virtualUserID}, timeAfterEventBefore),
createMessageEventsForBatchSendRequest([]string{virtualUserID}, timeAfterEventBefore, 2),
// Status
200,
)
batchSendResBody := client.ParseJSON(t, batchSendRes)
historicalEventIDs := client.GetJSONFieldStringArray(t, batchSendResBody, "event_ids")
// Join the room from a remote homeserver after the historical messages were sent
remoteCharlie.JoinRoom(t, roomID, []string{"hs1"})
// Make sure all of the events have been backfilled
fetchUntilMessagesResponseHas(t, remoteCharlie, roomID, func(ev gjson.Result) bool {
if ev.Get("event_id").Str == eventIdBefore {
return true
}
return false
})
messagesRes := remoteCharlie.MustDoFunc(t, "GET", []string{"_matrix", "client", "r0", "rooms", roomID, "messages"}, client.WithContentType("application/json"), client.WithQueries(url.Values{
"dir": []string{"b"},
"limit": []string{"100"},
}))
must.MatchResponse(t, messagesRes, match.HTTPResponse{
JSON: []match.JSON{
match.JSONCheckOffAllowUnwanted("chunk", makeInterfaceSlice(historicalEventIDs), func(r gjson.Result) interface{} {
return r.Get("event_id").Str
}, nil),
},
})
})
t.Run("Historical messages are visible when already joined on federated server", func(t *testing.T) {
t.Parallel()
roomID := as.CreateRoom(t, createPublicRoomOpts)
alice.JoinRoom(t, roomID, nil)
// Join the room from a remote homeserver before any historical messages are sent
remoteCharlie.JoinRoom(t, roomID, []string{"hs1"})
eventIDsBefore := createMessagesInRoom(t, alice, roomID, 1)
eventIdBefore := eventIDsBefore[0]
timeAfterEventBefore := time.Now()
// eventIDsAfter
createMessagesInRoom(t, alice, roomID, 10)
// Mimic scrollback just through the latest messages
remoteCharlie.MustDoFunc(t, "GET", []string{"_matrix", "client", "r0", "rooms", roomID, "messages"}, client.WithContentType("application/json"), client.WithQueries(url.Values{
"dir": []string{"b"},
// Limited so we can only see a portion of the latest messages
"limit": []string{"5"},
}))
numMessagesSent := 2
batchSendRes := batchSendHistoricalMessages(
t,
as,
roomID,
eventIdBefore,
"",
createJoinStateEventsForBatchSendRequest([]string{virtualUserID}, timeAfterEventBefore),
createMessageEventsForBatchSendRequest([]string{virtualUserID}, timeAfterEventBefore, numMessagesSent),
// Status
200,
)
batchSendResBody := client.ParseJSON(t, batchSendRes)
historicalEventIDs := client.GetJSONFieldStringArray(t, batchSendResBody, "event_ids")
baseInsertionEventID := client.GetJSONFieldStr(t, batchSendResBody, "base_insertion_event_id")
if len(historicalEventIDs) != numMessagesSent {
t.Fatalf("Expected %d event_ids in the response that correspond to the %d events we sent in the request but saw %d: %s", numMessagesSent, numMessagesSent, len(historicalEventIDs), historicalEventIDs)
}
beforeMarkerMessagesRes := remoteCharlie.MustDoFunc(t, "GET", []string{"_matrix", "client", "r0", "rooms", roomID, "messages"}, client.WithContentType("application/json"), client.WithQueries(url.Values{
"dir": []string{"b"},
"limit": []string{"100"},
}))
beforeMarkerMesssageResBody := client.ParseJSON(t, beforeMarkerMessagesRes)
eventDebugStringsFromBeforeMarkerResponse := getRelevantEventDebugStringsFromMessagesResponse(t, beforeMarkerMesssageResBody)
// Since the original body can only be read once, create a new one from the body bytes we just read
beforeMarkerMessagesRes.Body = ioutil.NopCloser(bytes.NewBuffer(beforeMarkerMesssageResBody))
// Make sure the history isn't visible before we expect it to be there.
// This is to avoid some bug in the homeserver using some unknown
// mechanism to distribute the historical messages to other homeservers.
must.MatchResponse(t, beforeMarkerMessagesRes, match.HTTPResponse{
JSON: []match.JSON{
match.JSONArrayEach("chunk", func(r gjson.Result) error {
// Throw if we find one of the historical events in the message response
for _, historicalEventID := range historicalEventIDs {
if r.Get("event_id").Str == historicalEventID {
return fmt.Errorf("Historical event (%s) found on remote homeserver before marker event was sent out\nmessage response (%d): %v\nhistoricalEventIDs (%d): %v", historicalEventID, len(eventDebugStringsFromBeforeMarkerResponse), eventDebugStringsFromBeforeMarkerResponse, len(historicalEventIDs), historicalEventIDs)
}
}
return nil
}),
},
})
// Send the marker event
sendMarkerAndEnsureBackfilled(t, as, remoteCharlie, roomID, baseInsertionEventID)
remoteMessagesRes := remoteCharlie.MustDoFunc(t, "GET", []string{"_matrix", "client", "r0", "rooms", roomID, "messages"}, client.WithContentType("application/json"), client.WithQueries(url.Values{
"dir": []string{"b"},
"limit": []string{"100"},
}))
// Make sure all of the historical messages are visible when we scrollback again
must.MatchResponse(t, remoteMessagesRes, match.HTTPResponse{
JSON: []match.JSON{
match.JSONCheckOffAllowUnwanted("chunk", makeInterfaceSlice(historicalEventIDs), func(r gjson.Result) interface{} {
return r.Get("event_id").Str
}, nil),
},
})
})
t.Run("When messages have already been scrolled back through, new historical messages are visible in next scroll back on federated server", func(t *testing.T) {
t.Parallel()
roomID := as.CreateRoom(t, createPublicRoomOpts)
alice.JoinRoom(t, roomID, nil)
// Join the room from a remote homeserver before any historical messages are sent
remoteCharlie.JoinRoom(t, roomID, []string{"hs1"})
eventIDsBefore := createMessagesInRoom(t, alice, roomID, 1)
eventIdBefore := eventIDsBefore[0]
timeAfterEventBefore := time.Now()
// eventIDsAfter
createMessagesInRoom(t, alice, roomID, 3)
// Mimic scrollback to all of the messages
// scrollbackMessagesRes
remoteCharlie.MustDoFunc(t, "GET", []string{"_matrix", "client", "r0", "rooms", roomID, "messages"}, client.WithContentType("application/json"), client.WithQueries(url.Values{
"dir": []string{"b"},
"limit": []string{"100"},
}))
// Historical messages are inserted where we have already scrolled back to
numMessagesSent := 2
batchSendRes := batchSendHistoricalMessages(
t,
as,
roomID,
eventIdBefore,
"",
createJoinStateEventsForBatchSendRequest([]string{virtualUserID}, timeAfterEventBefore),
createMessageEventsForBatchSendRequest([]string{virtualUserID}, timeAfterEventBefore, numMessagesSent),
// Status
200,
)
batchSendResBody := client.ParseJSON(t, batchSendRes)
historicalEventIDs := client.GetJSONFieldStringArray(t, batchSendResBody, "event_ids")
baseInsertionEventID := client.GetJSONFieldStr(t, batchSendResBody, "base_insertion_event_id")
if len(historicalEventIDs) != numMessagesSent {
t.Fatalf("Expected %d event_ids in the response that correspond to the %d events we sent in the request but saw %d: %s", numMessagesSent, numMessagesSent, len(historicalEventIDs), historicalEventIDs)
}
beforeMarkerMessagesRes := remoteCharlie.MustDoFunc(t, "GET", []string{"_matrix", "client", "r0", "rooms", roomID, "messages"}, client.WithContentType("application/json"), client.WithQueries(url.Values{
"dir": []string{"b"},
"limit": []string{"100"},
}))
beforeMarkerMesssageResBody := client.ParseJSON(t, beforeMarkerMessagesRes)
eventDebugStringsFromBeforeMarkerResponse := getRelevantEventDebugStringsFromMessagesResponse(t, beforeMarkerMesssageResBody)
// Since the original body can only be read once, create a new one from the body bytes we just read
beforeMarkerMessagesRes.Body = ioutil.NopCloser(bytes.NewBuffer(beforeMarkerMesssageResBody))
// Make sure the history isn't visible before we expect it to be there.
// This is to avoid some bug in the homeserver using some unknown
// mechanism to distribute the historical messages to other homeservers.
must.MatchResponse(t, beforeMarkerMessagesRes, match.HTTPResponse{
JSON: []match.JSON{
match.JSONArrayEach("chunk", func(r gjson.Result) error {
// Throw if we find one of the historical events in the message response
for _, historicalEventID := range historicalEventIDs {
if r.Get("event_id").Str == historicalEventID {
return fmt.Errorf("Historical event (%s) found on remote homeserver before marker event was sent out\nmessage response (%d): %v\nhistoricalEventIDs (%d): %v", historicalEventID, len(eventDebugStringsFromBeforeMarkerResponse), eventDebugStringsFromBeforeMarkerResponse, len(historicalEventIDs), historicalEventIDs)
}
}
return nil
}),
},
})
// Send the marker event
sendMarkerAndEnsureBackfilled(t, as, remoteCharlie, roomID, baseInsertionEventID)
remoteMessagesRes := remoteCharlie.MustDoFunc(t, "GET", []string{"_matrix", "client", "r0", "rooms", roomID, "messages"}, client.WithContentType("application/json"), client.WithQueries(url.Values{
"dir": []string{"b"},
"limit": []string{"100"},
}))
// Make sure all of the historical messages are visible when we scrollback again
must.MatchResponse(t, remoteMessagesRes, match.HTTPResponse{
JSON: []match.JSON{
match.JSONCheckOffAllowUnwanted("chunk", makeInterfaceSlice(historicalEventIDs), func(r gjson.Result) interface{} {
return r.Get("event_id").Str
}, nil),
},
})
})
t.Run("Existing room versions", func(t *testing.T) {
createUnsupportedMSC2716RoomOpts := map[string]interface{}{
"preset": "public_chat",
"name": "the hangout spot",
// v6 is an existing room version that does not support MSC2716
"room_version": "6",
}
t.Run("Room creator can send MSC2716 events", func(t *testing.T) {
t.Parallel()
roomID := as.CreateRoom(t, createUnsupportedMSC2716RoomOpts)
alice.JoinRoom(t, roomID, nil)
// Create the "live" event we are going to import our historical events next to
eventIDsBefore := createMessagesInRoom(t, alice, roomID, 1)
eventIdBefore := eventIDsBefore[0]
timeAfterEventBefore := time.Now()
// Create eventIDsAfter to avoid the "No forward extremities left!" 500 error from Synapse
createMessagesInRoom(t, alice, roomID, 2)
// Import a historical event
batchSendRes := batchSendHistoricalMessages(
t,
as,
roomID,
eventIdBefore,
"",
createJoinStateEventsForBatchSendRequest([]string{virtualUserID}, timeAfterEventBefore),
createMessageEventsForBatchSendRequest([]string{virtualUserID}, timeAfterEventBefore, 1),
// Status
200,
)
batchSendResBody := client.ParseJSON(t, batchSendRes)
historicalEventIDs := client.GetJSONFieldStringArray(t, batchSendResBody, "event_ids")
nextBatchID := client.GetJSONFieldStr(t, batchSendResBody, "next_batch_id")
messagesRes := alice.MustDoFunc(t, "GET", []string{"_matrix", "client", "r0", "rooms", roomID, "messages"}, client.WithContentType("application/json"), client.WithQueries(url.Values{
"dir": []string{"b"},
"limit": []string{"100"},
}))
must.MatchResponse(t, messagesRes, match.HTTPResponse{
JSON: []match.JSON{
match.JSONCheckOffAllowUnwanted("chunk", makeInterfaceSlice(historicalEventIDs), func(r gjson.Result) interface{} {
return r.Get("event_id").Str
}, nil),
},
})
// Now try to do a subsequent batch send. This will make sure
// that insertion events are stored/tracked and can be matched up in the next batch
batchSendHistoricalMessages(
t,
as,
roomID,
eventIdBefore,
nextBatchID,
createJoinStateEventsForBatchSendRequest([]string{virtualUserID}, timeAfterEventBefore),
createMessageEventsForBatchSendRequest([]string{virtualUserID}, timeAfterEventBefore, 1),
// Status
200,
)
})
t.Run("Not allowed to redact MSC2716 insertion, batch, marker events", func(t *testing.T) {
t.Parallel()
roomID := as.CreateRoom(t, createUnsupportedMSC2716RoomOpts)
alice.JoinRoom(t, roomID, nil)
// Create the "live" event we are going to import our historical events next to
eventIDsBefore := createMessagesInRoom(t, alice, roomID, 1)
eventIdBefore := eventIDsBefore[0]
timeAfterEventBefore := time.Now()
// Import a historical event
batchSendRes := batchSendHistoricalMessages(
t,
as,
roomID,
eventIdBefore,
"",
createJoinStateEventsForBatchSendRequest([]string{virtualUserID}, timeAfterEventBefore),
createMessageEventsForBatchSendRequest([]string{virtualUserID}, timeAfterEventBefore, 1),
// Status
200,
)
batchSendResBody := client.ParseJSON(t, batchSendRes)
insertionEventID := client.GetJSONFieldStr(t, batchSendResBody, "insertion_event_id")
batchEventID := client.GetJSONFieldStr(t, batchSendResBody, "batch_event_id")
baseInsertionEventID := client.GetJSONFieldStr(t, batchSendResBody, "base_insertion_event_id")
// Send the marker event
markerEventID := sendMarkerAndEnsureBackfilled(t, as, alice, roomID, baseInsertionEventID)
redactEventID(t, alice, roomID, insertionEventID, 403)
redactEventID(t, alice, roomID, batchEventID, 403)
redactEventID(t, alice, roomID, markerEventID, 403)
})
})
})
}
var txnCounter int = 0
func getTxnID(prefix string) (txnID string) {
txnId := fmt.Sprintf("%s-%d", prefix, txnCounter)
txnCounter++
return txnId
}
func makeInterfaceSlice(slice []string) []interface{} {
interfaceSlice := make([]interface{}, len(slice))
for i := range slice {
interfaceSlice[i] = slice[i]
}
return interfaceSlice
}
func reversed(in []string) []string {
out := make([]string, len(in))
for i := 0; i < len(in); i++ {
out[i] = in[len(in)-i-1]
}
return out
}
func fetchUntilMessagesResponseHas(t *testing.T, c *client.CSAPI, roomID string, check func(gjson.Result) bool) {
t.Helper()
start := time.Now()
checkCounter := 0
for {
if time.Since(start) > c.SyncUntilTimeout {
t.Fatalf("fetchUntilMessagesResponseHas timed out. Called check function %d times", checkCounter)
}
messagesRes := c.MustDoFunc(t, "GET", []string{"_matrix", "client", "r0", "rooms", roomID, "messages"}, client.WithContentType("application/json"), client.WithQueries(url.Values{
"dir": []string{"b"},
"limit": []string{"100"},
}))
messsageResBody := client.ParseJSON(t, messagesRes)
wantKey := "chunk"
keyRes := gjson.GetBytes(messsageResBody, wantKey)
if !keyRes.Exists() {
t.Fatalf("missing key '%s'", wantKey)
}
if !keyRes.IsArray() {
t.Fatalf("key '%s' is not an array (was %s)", wantKey, keyRes.Type)
}
events := keyRes.Array()
for _, ev := range events {
if check(ev) {
return
}
}
checkCounter++
// Add a slight delay so we don't hammmer the messages endpoint
time.Sleep(500 * time.Millisecond)
}
}
func isRelevantEvent(r gjson.Result) bool {
return len(r.Get("content").Get("body").Str) > 0 ||
r.Get("type").Str == insertionEventType ||
r.Get("type").Str == batchEventType ||
r.Get("type").Str == markerEventType
}
func getRelevantEventDebugStringsFromMessagesResponse(t *testing.T, body []byte) (eventIDsFromResponse []string) {
t.Helper()
wantKey := "chunk"
res := gjson.GetBytes(body, wantKey)
if !res.Exists() {
t.Fatalf("missing key '%s'", wantKey)
}
if !res.IsArray() {
t.Fatalf("key '%s' is not an array (was %s)", wantKey, res.Type)
}
res.ForEach(func(key, r gjson.Result) bool {
if isRelevantEvent(r) {
eventIDsFromResponse = append(eventIDsFromResponse, r.Get("event_id").Str+" ("+r.Get("content").Get("body").Str+")")
}
return true
})
return eventIDsFromResponse
}
// ensureVirtualUserRegistered makes sure the user is registered for the homeserver regardless
// if they are already registered or not. If unable to register, fails the test
func ensureVirtualUserRegistered(t *testing.T, c *client.CSAPI, virtualUserLocalpart string) {
res := c.DoFunc(
t,
"POST",
[]string{"_matrix", "client", "r0", "register"},