forked from ably/ably-dotnet
/
PresenceSandboxSpecs.cs
1953 lines (1650 loc) · 85.7 KB
/
PresenceSandboxSpecs.cs
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using IO.Ably.Realtime;
using IO.Ably.Tests.Infrastructure;
using IO.Ably.Transport;
using IO.Ably.Transport.States.Connection;
using IO.Ably.Types;
using Xunit;
using Xunit.Abstractions;
namespace IO.Ably.Tests.Realtime
{
[Collection("Presence Sandbox")]
[Trait("requires", "sandbox")]
public class PresenceSandboxSpecs : SandboxSpecs
{
public class GeneralPresenceSandBoxSpecs : PresenceSandboxSpecs
{
public GeneralPresenceSandBoxSpecs(AblySandboxFixture fixture, ITestOutputHelper output)
: base(fixture, output)
{
}
// TODO: Add tests to makes sure Presense messages id, timestamp and connectionId are set
[Theory]
[ProtocolData]
[Trait("spec", "RTP1")]
public async Task WhenAttachingToAChannelWithNoMembers_PresenceShouldBeConsideredInSync(Protocol protocol)
{
var client = await GetRealtimeClient(protocol);
var channel = client.Channels.Get(GetTestChannelName());
await channel.AttachAsync();
await channel.WaitForState(ChannelState.Attached);
channel.Presence.SyncComplete.Should().BeTrue();
}
[Theory]
[ProtocolData]
[Trait("spec", "RTP1")]
public async Task WhenAttachingToAChannelWithMembers_PresenceShouldBeInProgress(Protocol protocol)
{
Logger.LogLevel = LogLevel.Debug;
var testChannel = GetTestChannelName();
var client = await GetRealtimeClient(protocol);
var client2 = await GetRealtimeClient(protocol);
var channel = client.Channels.Get(testChannel);
List<Task> tasks = new List<Task>();
for (int count = 1; count < 10; count++)
{
tasks.Add(channel.Presence.EnterClientAsync($"client-{count}", null));
}
await Task.WhenAll(tasks.ToArray());
var channel2 = client2.Channels.Get(testChannel) as RealtimeChannel;
int inSync = 0;
int syncComplete = 0;
channel2.InternalStateChanged += (_, args) =>
{
if (args.Current == ChannelState.Attached)
{
Logger.Debug("Test: Setting inSync to - " + channel2.Presence.Map.IsSyncInProgress);
Interlocked.Add(ref inSync, channel2.Presence.Map.IsSyncInProgress ? 1 : 0);
Interlocked.Add(ref syncComplete, channel2.Presence.InternalSyncComplete ? 1 : 0);
}
};
await channel2.AttachAsync();
await Task.Delay(1000);
inSync.Should().Be(1);
syncComplete.Should().Be(0);
}
/*
* Test presence message map behaviour (RTP2 features)
* Tests RTP2a, RTP2b1, RTP2b2, RTP2c, RTP2d, RTP2g, RTP18c, RTP6a features
*/
[Theory]
[ProtocolData]
[Trait("spec", "RTP2")]
[Trait("spec", "RTP2a")]
[Trait("spec", "RTP2b1")]
[Trait("spec", "RTP2b2")]
[Trait("spec", "RTP2c")]
[Trait("spec", "RTP2d")]
[Trait("spec", "RTP2g")]
[Trait("spec", "RTP6a")]
[Trait("spec", "RTP18c")]
public async Task PresenceMapBehaviour_ShouldConformToSpec(Protocol protocol)
{
Logger.LogLevel = LogLevel.Debug;
var channelName = "presence_map_tests_newness".AddRandomSuffix();
var client = await GetRealtimeClient(protocol);
await client.WaitForState(ConnectionState.Connected);
client.Connection.State.ShouldBeEquivalentTo(ConnectionState.Connected);
var channel = client.Channels.Get(channelName);
channel.Attach();
await channel.WaitForState(ChannelState.Attached);
channel.State.ShouldBeEquivalentTo(ChannelState.Attached);
const string wontPass = "Won't pass newness test";
List<PresenceMessage> presenceMessages = new List<PresenceMessage>();
channel.Presence.Subscribe(x =>
{
x.Data.Should().NotBe(wontPass, "message did not pass the newness test");
presenceMessages.Add(x);
});
/* Test message newness criteria as described in RTP2b */
PresenceMessage[] testData = new PresenceMessage[]
{
new PresenceMessage
{
Action = PresenceAction.Enter,
ClientId = "1",
ConnectionId = "1",
Id = "1:0",
Data = string.Empty
},
new PresenceMessage
{
Action = PresenceAction.Enter,
ClientId = "2",
ConnectionId = "2",
Id = "2:1:0",
Timestamp = new DateTimeOffset(2000, 1, 1, 1, 1, 1, default(TimeSpan)),
Data = string.Empty
},
/* Should be newer than previous one */
new PresenceMessage
{
Action = PresenceAction.Update,
ClientId = "2",
ConnectionId = "2",
Id = "2:2:1",
Timestamp = new DateTimeOffset(2000, 1, 1, 1, 1, 2, default(TimeSpan)),
Data = string.Empty
},
/* Shouldn't pass newness test because of message serial, timestamp doesn't matter in this case */
new PresenceMessage
{
Action = PresenceAction.Update,
ClientId = "2",
ConnectionId = "2",
Id = "2:1:1",
Timestamp = new DateTimeOffset(2000, 1, 1, 1, 1, 3, default(TimeSpan)),
Data = wontPass
},
/* Shouldn't pass because of message index */
new PresenceMessage
{
Action = PresenceAction.Update,
ClientId = "2",
ConnectionId = "2",
Id = "2:2:0",
Data = wontPass
},
/* Should pass because id is not in form connId:clientId:index and timestamp is greater */
new PresenceMessage
{
Action = PresenceAction.Update,
ClientId = "2",
ConnectionId = "2",
Id = "wrong_id",
Timestamp = new DateTimeOffset(2000, 1, 1, 1, 1, 10, default(TimeSpan)),
Data = string.Empty
},
/* Shouldn't pass because of timestamp */
new PresenceMessage
{
Action = PresenceAction.Update,
ClientId = "2",
ConnectionId = "2",
Id = "2:3:1",
Timestamp = new DateTimeOffset(2000, 1, 1, 1, 1, 5, default(TimeSpan)),
Data = wontPass
}
};
foreach (var presenceMessage in testData)
{
var protocolMessage = new ProtocolMessage(ProtocolMessage.MessageAction.Presence)
{
Channel = channelName,
Presence = new PresenceMessage[] { presenceMessage }
};
await client.Connection.ConnectionManager.OnTransportMessageReceived(protocolMessage);
}
int n = 0;
foreach (var testMsg in testData)
{
if (testMsg.Data.ToString() == wontPass)
{
continue;
}
PresenceMessage factualMsg = n < presenceMessages.Count ? presenceMessages[n++] : null;
factualMsg.Should().NotBe(null);
factualMsg.Id.ShouldBeEquivalentTo(testMsg.Id);
factualMsg.Action.ShouldBeEquivalentTo(testMsg.Action, "message was not emitted on the presence object with original action");
var presentMessage = await channel.Presence.GetAsync(new Presence.GetParams
{
ClientId = testMsg.ClientId, WaitForSync = false
});
presentMessage.FirstOrDefault().Should().NotBe(null);
presentMessage.FirstOrDefault()?.Action.ShouldBeEquivalentTo(PresenceAction.Present, "message was not added to the presence map and stored with PRESENT action");
}
presenceMessages.Count.ShouldBeEquivalentTo(n, "the number of messages received didn't match the number of test messages sent.");
/* Repeat the process now as a part of SYNC and verify everything is exactly the same */
var channel2Name = "presence_map_tests_sync_newness".AddRandomSuffix();
var client2 = await GetRealtimeClient(protocol);
await client2.WaitForState(ConnectionState.Connected);
client2.Connection.State.ShouldBeEquivalentTo(ConnectionState.Connected);
var channel2 = client2.Channels.Get(channel2Name);
channel2.Attach();
await channel2.WaitForState(ChannelState.Attached);
channel2.State.ShouldBeEquivalentTo(ChannelState.Attached);
/* Send all the presence data in one SYNC message without channelSerial (RTP18c) */
ProtocolMessage syncMessage = new ProtocolMessage()
{
Channel = channel2Name,
Action = ProtocolMessage.MessageAction.Sync,
Presence = testData
};
var counter = new TaskCountAwaiter(presenceMessages.Count, 5000);
List<PresenceMessage> syncPresenceMessages = new List<PresenceMessage>();
channel2.Presence.Subscribe(x =>
{
x.Data.Should().NotBe(wontPass, "message did not pass the newness test");
syncPresenceMessages.Add(x);
counter.Tick();
});
await client2.Connection.ConnectionManager.OnTransportMessageReceived(syncMessage);
await counter.Task;
syncPresenceMessages.Count.ShouldBeEquivalentTo(presenceMessages.Count);
for (int i = 0; i < syncPresenceMessages.Count; i++)
{
syncPresenceMessages[i].Id.ShouldBeEquivalentTo(presenceMessages[i].Id, "result should be the same in case of SYNC");
syncPresenceMessages[i].Action.ShouldBeEquivalentTo(presenceMessages[i].Action, "result should be the same in case of SYNC");
}
}
[Theory]
[ProtocolData]
[Trait("spec", "RTP17")]
[Trait("spec", "RTP17b")]
public async Task Presence_ShouldHaveInternalMapForCurrentConnectionId(Protocol protocol)
{
/*
* any ENTER, PRESENT, UPDATE or LEAVE event that matches
* the current connectionId should be applied to the internal map
*/
var channelName = "RTP17".AddRandomSuffix();
var clientA = await GetRealtimeClient(protocol, (options, settings) => { options.ClientId = "A"; });
var channelA = clientA.Channels.Get(channelName);
var clientB = await GetRealtimeClient(protocol, (options, settings) => { options.ClientId = "B"; });
var channelB = clientB.Channels.Get(channelName);
// ENTER
PresenceMessage msgA = null, msgB = null;
await WaitForMultiple(2, partialDone =>
{
channelA.Presence.Subscribe(msg =>
{
msgA = msg;
partialDone();
});
channelB.Presence.Subscribe(msg =>
{
msgB = msg;
partialDone();
});
channelA.Presence.Enter("chA");
});
msgA.Should().NotBeNull();
msgA.Action.Should().Be(PresenceAction.Enter);
msgA.ConnectionId.Should().Be(clientA.Connection.Id);
channelA.Presence.Map.Members.Should().HaveCount(1);
channelA.Presence.InternalMap.Members.Should().HaveCount(1);
channelA.Presence.Unsubscribe();
msgB.Should().NotBeNull();
msgB.Action.Should().Be(PresenceAction.Enter);
msgB.ConnectionId.Should().NotBe(clientB.Connection.Id);
channelB.Presence.Map.Members.Should().HaveCount(1);
channelB.Presence.InternalMap.Members.Should().HaveCount(0);
channelB.Presence.Unsubscribe();
msgA = null;
msgB = null;
await WaitForMultiple(2, partialDone =>
{
channelA.Presence.Subscribe(msg =>
{
msgA = msg;
channelA.Presence.Unsubscribe();
partialDone();
});
channelB.Presence.Subscribe(msg =>
{
msgB = msg;
channelB.Presence.Unsubscribe();
partialDone();
});
channelB.Presence.Enter("chB");
});
msgA.Should().NotBeNull();
msgA.Action.Should().Be(PresenceAction.Enter);
msgA.ConnectionId.Should().NotBe(clientA.Connection.Id);
channelA.Presence.Map.Members.Should().HaveCount(2);
channelA.Presence.InternalMap.Members.Should().HaveCount(1);
msgB.Should().NotBeNull();
msgB.Action.Should().Be(PresenceAction.Enter);
msgB.ConnectionId.Should().Be(clientB.Connection.Id);
channelB.Presence.Map.Members.Should().HaveCount(2);
channelB.Presence.InternalMap.Members.Should().HaveCount(1);
// UPDATE
msgA = null;
msgB = null;
await WaitForMultiple(2, partialDone =>
{
channelA.Presence.Subscribe(msg =>
{
msgA = msg;
channelA.Presence.Unsubscribe();
partialDone();
});
channelB.Presence.Subscribe(msg =>
{
msgB = msg;
channelB.Presence.Unsubscribe();
partialDone();
});
channelB.Presence.Update("chB-update");
});
msgA.Should().NotBeNull();
msgA.Action.Should().Be(PresenceAction.Update);
msgA.ConnectionId.Should().NotBe(clientA.Connection.Id);
msgA.Data.ToString().Should().Be("chB-update");
channelA.Presence.Map.Members.Should().HaveCount(2);
channelA.Presence.InternalMap.Members.Should().HaveCount(1);
msgB.Should().NotBeNull();
msgB.Action.Should().Be(PresenceAction.Update);
msgB.ConnectionId.Should().Be(clientB.Connection.Id);
msgB.Data.ToString().Should().Be("chB-update");
channelB.Presence.Map.Members.Should().HaveCount(2);
channelB.Presence.InternalMap.Members.Should().HaveCount(1);
// LEAVE with synthesized message
msgA = null;
msgB = null;
await WaitForMultiple(2, partialDone =>
{
channelA.Presence.Subscribe(msg =>
{
msgA = msg;
channelA.Presence.Unsubscribe();
partialDone();
});
channelB.Presence.Subscribe(msg =>
{
msgB = msg;
channelB.Presence.Unsubscribe();
partialDone();
});
channelB.Presence.Leave("chB-leave");
});
msgA.Should().NotBeNull();
msgA.Action.Should().Be(PresenceAction.Leave);
msgA.ConnectionId.Should().NotBe(clientA.Connection.Id);
msgA.Data.ToString().Should().Be("chB-leave");
channelA.Presence.Map.Members.Should().HaveCount(1);
channelA.Presence.InternalMap.Members.Should().HaveCount(1);
msgB.Should().NotBeNull();
msgB.Action.Should().Be(PresenceAction.Leave);
msgB.ConnectionId.Should().Be(clientB.Connection.Id);
msgB.Data.ToString().Should().Be("chB-leave");
channelB.Presence.Map.Members.Should().HaveCount(1);
channelB.Presence.InternalMap.Members.Should().HaveCount(0);
msgA = null;
msgB = null;
await WaitForMultiple(2, partialDone =>
{
channelA.Presence.Subscribe(msg =>
{
msgA = msg;
channelA.Presence.Unsubscribe();
partialDone();
});
var synthesizedMsg = new PresenceMessage(PresenceAction.Leave, clientB.ClientId) { ConnectionId = null };
synthesizedMsg.IsSynthesized().Should().BeTrue();
channelB.Presence.OnPresence(new[] { synthesizedMsg }, null);
partialDone();
});
msgA.Should().NotBeNull();
msgA.Action.Should().Be(PresenceAction.Leave);
msgA.ConnectionId.Should().NotBe(clientA.Connection.Id);
msgA.Data.ToString().Should().Be("chB-leave");
channelA.Presence.Map.Members.Should().HaveCount(1);
channelA.Presence.InternalMap.Members.Should().HaveCount(1);
msgB.Should().BeNull();
channelB.Presence.Map.Members.Should().HaveCount(1);
// message was synthesized so should not have been removed (RTP17b)
channelB.Presence.InternalMap.Members.Should().HaveCount(1);
// clean up
clientA.Close();
clientB.Close();
}
[Theory]
[ProtocolData]
[Trait("spec", "RTP17a")]
public async Task Presence_ShouldPublishAllMembersForTheCurrentConnection(Protocol protocol)
{
var channelName = "RTP17a".AddRandomSuffix();
var clientId = "RTP17a-client".AddRandomSuffix();
var capability = new Capability();
capability.AddResource(channelName).AllowPresence().AllowPublish();
var client = await GetRealtimeClient(protocol, (options, settings) =>
{
options.DefaultTokenParams = new TokenParams { Capability = capability, ClientId = clientId };
});
var channel = client.Channels.Get(channelName);
var result = await channel.Presence.EnterClientAsync(clientId, null);
result.IsSuccess.Should().BeTrue();
var members = await channel.Presence.GetAsync();
members.Should().HaveCount(1);
channel.Presence.Map.Members.Should().HaveCount(1);
channel.Presence.InternalMap.Members.Should().HaveCount(1);
}
[Theory]
[ProtocolData]
[Trait("spec", "RTP2e")]
public async Task PresenceMap_WhenNotSyncingAndLeaveActionArrivesMemberKeyShouldBeDeleted(Protocol protocol)
{
// setup 20 members on a channel
var channelName = "RTP2e".AddRandomSuffix();
var setupClient = await GetRealtimeClient(protocol);
await setupClient.WaitForState(ConnectionState.Connected);
var setupChannel = setupClient.Channels.Get(channelName);
setupChannel.Attach();
await setupChannel.WaitForState();
for (int i = 0; i < 20; i++)
{
await setupChannel.Presence.EnterClientAsync($"member_{i}", null);
}
var client = await GetRealtimeClient(protocol);
await client.WaitForState(ConnectionState.Connected);
var channel = client.Channels.Get(channelName);
channel.Attach();
await channel.WaitForState();
// get presence messages and validate count
var members = await channel.Presence.GetAsync();
members.Should().HaveCount(20);
// sync should not be in progress and initial an sync should have completed
channel.Presence.IsSyncInProgress.Should().BeFalse("sync should have completed");
channel.Presence.SyncComplete.Should().BeTrue();
// pull a random member key from the presence map
var memberNumber = new Random().Next(0, 19);
var memberId = $"member_{memberNumber}";
var expectedMemberKey = $"{memberId}:{setupClient.Connection.Id}";
var actualMemberKey = channel.Presence.Map.Members[expectedMemberKey].MemberKey;
actualMemberKey.Should().Be(expectedMemberKey);
// wait for the member to leave
string leftClientId = null;
await WaitFor(done =>
{
channel.Presence.Subscribe(PresenceAction.Leave, message =>
{
leftClientId = message.ClientId;
done();
});
setupChannel.Presence.LeaveClient(memberId, null);
});
// then assert that the member has left
leftClientId.Should().Be(memberId);
channel.Presence.Map.Members.Should().HaveCount(19);
channel.Presence.Map.Members.ContainsKey(actualMemberKey).Should().BeFalse();
}
[Theory]
[ProtocolData]
[Trait("spec", "RTP2f")]
[Trait("spec", "RTP18a")]
[Trait("spec", "RTP18b")]
public async Task PresenceMap_WhenSyncingLeaveStoredAsAbsentAndDeleted(Protocol protocol)
{
Logger.LogLevel = LogLevel.Debug;
var channelName = "presence_map_tests_newness".AddRandomSuffix();
var client = await GetRealtimeClient(protocol);
await client.WaitForState(ConnectionState.Connected);
client.Connection.State.ShouldBeEquivalentTo(ConnectionState.Connected);
var channel = client.Channels.Get(channelName);
channel.Attach();
await channel.WaitForState(ChannelState.Attached);
channel.State.ShouldBeEquivalentTo(ChannelState.Attached);
PresenceMessage[] TestPresence1()
{
return new PresenceMessage[]
{
new PresenceMessage
{
Action = PresenceAction.Enter,
ClientId = "1",
ConnectionId = "1",
Id = "1:0",
Data = string.Empty
},
};
}
PresenceMessage[] TestPresence2()
{
return new PresenceMessage[]
{
new PresenceMessage
{
Action = PresenceAction.Enter,
ClientId = "2",
ConnectionId = "2",
Id = "2:1:0",
Data = string.Empty
},
new PresenceMessage
{
Action = PresenceAction.Enter,
ClientId = "3",
ConnectionId = "3",
Id = "3:1:0",
Data = string.Empty
},
};
}
PresenceMessage[] TestPresence3()
{
return new PresenceMessage[]
{
new PresenceMessage
{
Action = PresenceAction.Leave,
ClientId = "3",
ConnectionId = "3",
Id = "3:0:0",
Data = string.Empty
},
new PresenceMessage
{
Action = PresenceAction.Enter,
ClientId = "4",
ConnectionId = "4",
Id = "4:1:1",
Data = string.Empty
},
new PresenceMessage
{
Action = PresenceAction.Leave,
ClientId = "4",
ConnectionId = "4",
Id = "4:2:2",
Data = string.Empty
},
};
}
bool seenLeaveMessageAsAbsentForClient4 = false;
List<PresenceMessage> presenceMessagesLog = new List<PresenceMessage>();
channel.Presence.Subscribe(message =>
{
// keep track of the all presence messages we receive
presenceMessagesLog.Add(message);
});
channel.Presence.Subscribe(PresenceAction.Leave, async message =>
{
/*
* Do not call it in states other than ATTACHED because of presence.get() side
* effect of attaching channel
*/
if (message.ClientId == "4" && message.Action == PresenceAction.Leave && channel.State == ChannelState.Attached)
{
/*
* Client library won't return a presence message if it is stored as ABSENT
* so the result of the presence.get() call should be empty.
*/
var result = await channel.Presence.GetAsync("4", waitForSync: false);
seenLeaveMessageAsAbsentForClient4 = result.ToArray().Length == 0;
}
});
await client.Connection.ConnectionManager.OnTransportMessageReceived(new ProtocolMessage()
{
Action = ProtocolMessage.MessageAction.Sync,
Channel = channelName,
ChannelSerial = "1:1",
Presence = TestPresence1()
});
await client.Connection.ConnectionManager.OnTransportMessageReceived(new ProtocolMessage()
{
Action = ProtocolMessage.MessageAction.Sync,
Channel = channelName,
ChannelSerial = "2:1",
Presence = TestPresence2()
});
await client.Connection.ConnectionManager.OnTransportMessageReceived(new ProtocolMessage()
{
Action = ProtocolMessage.MessageAction.Sync,
Channel = channelName,
ChannelSerial = "2:",
Presence = TestPresence3()
});
var presence1 = await channel.Presence.GetAsync("1", false);
var presence2 = await channel.Presence.GetAsync("2", false);
var presence3 = await channel.Presence.GetAsync("3", false);
var presenceOthers = await channel.Presence.GetAsync();
presence1.ToArray().Length.ShouldBeEquivalentTo(0, "incomplete sync should be discarded");
presence2.ToArray().Length.ShouldBeEquivalentTo(1, "client with id==2 should be in presence map");
presence3.ToArray().Length.ShouldBeEquivalentTo(1, "client with id==3 should be in presence map");
presenceOthers.ToArray().Length.ShouldBeEquivalentTo(2, "presence map should be empty");
seenLeaveMessageAsAbsentForClient4.ShouldBeEquivalentTo(true, "LEAVE message for client with id==4 was not stored as ABSENT");
PresenceMessage[] correctPresenceHistory = new PresenceMessage[]
{
/* client 1 enters (will later be discarded) */
new PresenceMessage(PresenceAction.Enter, "1"),
/* client 2 enters */
new PresenceMessage(PresenceAction.Enter, "2"),
/* client 3 enters and never leaves because of newness comparison for LEAVE fails */
new PresenceMessage(PresenceAction.Enter, "3"),
/* client 4 enters and leaves */
new PresenceMessage(PresenceAction.Enter, "4"),
new PresenceMessage(PresenceAction.Leave, "4"), /* geting dupe */
/* client 1 is eliminated from the presence map because the first portion of SYNC is discarded */
new PresenceMessage(PresenceAction.Leave, "1")
};
presenceMessagesLog.Count.ShouldBeEquivalentTo(correctPresenceHistory.Length);
for (int i = 0; i < correctPresenceHistory.Length; i++)
{
PresenceMessage factualMsg = presenceMessagesLog[i];
PresenceMessage correctMsg = correctPresenceHistory[i];
factualMsg.ClientId.ShouldBeEquivalentTo(correctMsg.ClientId);
factualMsg.Action.ShouldBeEquivalentTo(correctMsg.Action);
}
}
[Theory]
[ProtocolData]
[Trait("spec", "RTP3")]
public async Task Presence_AfterReconnectingShouldReattachChannelAndResumeBrokenSync(Protocol protocol)
{
var channelName = "RTP3".AddRandomSuffix();
// must be greater than 100 to break up sync into multiple messages
var enterCount = 150;
var setupClient = await GetRealtimeClient(protocol);
await setupClient.WaitForState(ConnectionState.Connected);
// setup: enter clients on channel
var testChannel = setupClient.Channels.Get(channelName);
await testChannel.WaitForState(ChannelState.Attached);
testChannel.Presence.Subscribe(PresenceAction.Enter, message => { });
for (int i = 0; i < enterCount; i++)
{
var clientId = $"fakeclient:{i}";
await testChannel.Presence.EnterClientAsync(clientId, $"RTP3 test entry {i}");
}
var client = await GetRealtimeClient(protocol, (options, _) =>
{
Logger.LogLevel = LogLevel.Debug;
});
await client.WaitForState();
var channel = client.Channels.Get(channelName);
var transport = client.GetTestTransport();
int syncCount = 0;
transport.AfterDataReceived = protocolMessage =>
{
if (protocolMessage.Action == ProtocolMessage.MessageAction.Sync)
{
syncCount++;
// interrupt after first page of results
if (syncCount == 2)
{
transport.Close(false);
}
}
};
channel.Attach();
await channel.WaitForState(ChannelState.Attached);
channel.State.Should().Be(ChannelState.Attached);
await client.WaitForState(ConnectionState.Disconnected);
client.Connection.State.Should().Be(ConnectionState.Disconnected);
await client.WaitForState(ConnectionState.Connected);
client.Connection.State.Should().Be(ConnectionState.Connected);
await Task.Delay(500);
var messages = await channel.Presence.GetAsync();
var messageList = messages as IList<PresenceMessage> ?? messages.ToList();
messageList.Count.ShouldBeEquivalentTo(enterCount, "Message count should match enterCount");
syncCount.Should().Be(2);
transport.AfterDataReceived = null;
setupClient.Close();
client.Close();
}
[Theory]
[ProtocolData]
[Trait("spec", "RTP11")]
[Trait("spec", "RTP11b")]
[Trait("spec", "RTP11c")]
[Trait("spec", "RTP11c1")]
[Trait("spec", "RTP11c2")]
[Trait("spec", "RTP11c3")]
[Trait("spec", "RTP11d")]
public async Task Presence_GetMethodBehaviour(Protocol protocol)
{
string channelName = "RTP11".AddRandomSuffix();
var client1 = await GetRealtimeClient(protocol);
var client2 = await GetRealtimeClient(protocol, (options, settings) => options.AutoConnect = false);
var channel1 = client1.Channels.Get(channelName);
await channel1.Presence.EnterClientAsync("1", "one");
await channel1.Presence.EnterClientAsync("2", "two");
var channel2 = client2.Channels.Get(channelName);
var ch2Awaiter = new PresenceAwaiter(channel2);
// with waitForSync set to false,
// should result in 0 members because autoConnect is set to false
var presenceMessages1 = await channel2.Presence.GetAsync(false);
presenceMessages1.Should().HaveCount(0);
client2.Connection.Connect();
// With waitForSync is true it should get all the members entered on the first connection
var presenceMessages2 = await channel2.Presence.GetAsync(true);
presenceMessages2.Should().HaveCount(2);
// enter third member from second connection
await channel2.Presence.EnterClientAsync("3", null);
// wait for the above to raise a subscribe event
await ch2Awaiter.WaitFor(1);
// filter by clientId
var presenceMessages3 = await channel2.Presence.GetAsync("1");
presenceMessages3.Should().HaveCount(1);
presenceMessages3.First().ClientId.Should().Be("1");
// filter by connectionId
var presenceMessages4 = await channel2.Presence.GetAsync(connectionId: client2.Connection.Id);
presenceMessages4.Should().HaveCount(1);
presenceMessages4.First().ClientId.Should().Be("3");
// filter by both clientId and connectionId
var presenceMessages5 = await channel2.Presence.GetAsync(connectionId: client1.Connection.Id, clientId: "2");
var presenceMessages6 = await channel2.Presence.GetAsync(connectionId: client2.Connection.Id, clientId: "2");
presenceMessages5.Should().HaveCount(1);
presenceMessages6.Should().HaveCount(0);
presenceMessages5.First().ClientId.Should().Be("2");
// become SUSPENDED
await client2.ConnectionManager.SetState(new ConnectionSuspendedState(client2.ConnectionManager, Logger));
await client2.WaitForState(ConnectionState.Suspended);
// with waitForSync set to false, should get all the three members
var presenceMessages7 = await channel2.Presence.GetAsync(false);
presenceMessages7.Should().HaveCount(3);
// with waitForSync set to true, should get exception
client2.Connection.State.Should().Be(ConnectionState.Suspended);
try
{
await channel2.Presence.GetAsync(true);
throw new Exception("waitForSync=true shouldn't succeed in SUSPENDED state");
}
catch (AblyException e)
{
e.ErrorInfo.Code.Should().Be(91005);
}
}
[Theory]
[ProtocolData]
[Trait("spec", "RTP19")]
public async Task PresenceMap_WithExistingMembers_WhenSync_ShouldRemoveLocalMembers_RTP19(Protocol protocol)
{
var channelName = "RTP19".AddRandomSuffix();
var client = await GetRealtimeClient(protocol);
var channel = client.Channels.Get(channelName);
// ENTER presence on a channel
await channel.Presence.EnterClientAsync("1", "one");
await channel.Presence.EnterClientAsync("2", "two");
channel.Presence.Map.Members.Should().HaveCount(2);
var localMessage = new PresenceMessage()
{
Action = PresenceAction.Enter,
Id = $"local:0:0",
Timestamp = DateTimeOffset.UtcNow,
ClientId = "local".AddRandomSuffix(),
ConnectionId = "local",
Data = "local data"
};
// inject a member directly into the local PresenceMap
channel.Presence.Map.Members[localMessage.MemberKey] = localMessage;
channel.Presence.Map.Members.Should().HaveCount(3);
channel.Presence.Map.Members.ContainsKey(localMessage.MemberKey).Should().BeTrue();
var members = (await channel.Presence.GetAsync()).ToArray();
members.Should().HaveCount(3);
members.Where(m => m.ClientId == "1").Should().HaveCount(1);
var leaveMessages = new List<PresenceMessage>();
await WaitFor(async done =>
{
channel.Presence.Subscribe(PresenceAction.Leave, message =>
{
leaveMessages.Add(message);
done();
});
// trigger a server initiated SYNC
await client.ConnectionManager.SetState(new ConnectionSuspendedState(client.ConnectionManager, new ErrorInfo("RTP19 test"), client.Logger));
await client.WaitForState(ConnectionState.Suspended);
await client.ConnectionManager.SetState(new ConnectionConnectedState(client.ConnectionManager, null));
await client.WaitForState(ConnectionState.Connected);
});
// A LEAVE event should have be published for the injected member
leaveMessages.Should().HaveCount(1);
leaveMessages[0].ClientId.Should().Be(localMessage.ClientId);
// valid members entered for this connection are still present
members = (await channel.Presence.GetAsync()).ToArray();
members.Should().HaveCount(2);
members.Any(m => m.ClientId == localMessage.ClientId).Should().BeFalse();
}
[Theory]
[ProtocolData]
[Trait("spec", "RTP19a")]
[Trait("spec", "RTP6b")]
public async Task PresenceMap_WithExistingMembers_WhenBecomesAttachedWithoutHasPresence_ShouldEmitLeavesForExistingMembers(Protocol protocol)
{
/* (RTP19a) If the PresenceMap has existing members when an ATTACHED message
is received without a HAS_PRESENCE flag, the client library should emit a
LEAVE event for each existing member, and the PresenceMessage published should
contain the original attributes of the presence member with the action set to LEAVE,
PresenceMessage#id set to null, and the timestamp set to the current time. Once complete,
all members in the PresenceMap should be removed as there are no members present on the channel
*/
var channelName = "RTP19a".AddRandomSuffix();
var client = await GetRealtimeClient(protocol);
await client.WaitForState();
var channel = client.Channels.Get(channelName);
var localMessage1 = new PresenceMessage()
{
Action = PresenceAction.Enter,
Id = $"local:0:1",
Timestamp = DateTimeOffset.UtcNow,
ClientId = "local".AddRandomSuffix(),
ConnectionId = "local",
Data = "local data 1"
};
var localMessage2 = new PresenceMessage()
{
Action = PresenceAction.Enter,
Id = $"local:0:2",
Timestamp = DateTimeOffset.UtcNow,
ClientId = "local".AddRandomSuffix(),
ConnectionId = "local",
Data = "local data 2"
};
// inject a members directly into the local PresenceMap
channel.Presence.Map.Members[localMessage1.MemberKey] = localMessage1;
channel.Presence.Map.Members[localMessage2.MemberKey] = localMessage2;
channel.Presence.Map.Members.Should().HaveCount(2);
bool hasPresence = true;
int leaveCount = 0;
await WaitForMultiple(4, partialDone =>
{
client.GetTestTransport().AfterDataReceived += message =>
{
if (message.Action == ProtocolMessage.MessageAction.Attached)
{
hasPresence = message.HasFlag(ProtocolMessage.Flag.HasPresence);
partialDone();
}
};
// (RTP6b) Subscribe with a single action argument
channel.Presence.Subscribe(PresenceAction.Leave, leaveMsg =>
{
leaveMsg.ClientId.Should().StartWith("local");
leaveMsg.Action.Should().Be(PresenceAction.Leave, "Action shold be leave");
leaveMsg.Timestamp.Should().BeCloseTo(DateTime.UtcNow, 200, "timestamp should be current time" );
leaveMsg.Id.Should().BeNull("Id should be null");
leaveCount++;
partialDone(); // should be called twice
});
channel.Attach((b, info) =>
{
b.Should().BeTrue();
info.Should().BeNull();
partialDone();
});
});
hasPresence.Should().BeFalse("ATTACHED message was received without a HAS_PRESENCE flag");
leaveCount.Should().Be(2, "should emit a LEAVE event for each existing member");
var members = await channel.Presence.GetAsync();
members.Should().HaveCount(0, "should be no members");