summary refs log tree commit diff
path: root/tests/handlers/test_presence.py
blob: 41c8c44e02411b87cb614c24d2fb7f052189777c (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
# Copyright 2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import Optional, cast
from unittest.mock import Mock, call

from parameterized import parameterized
from signedjson.key import generate_signing_key

from twisted.test.proto_helpers import MemoryReactor

from synapse.api.constants import EventTypes, Membership, PresenceState
from synapse.api.presence import UserDevicePresenceState, UserPresenceState
from synapse.api.room_versions import KNOWN_ROOM_VERSIONS
from synapse.events.builder import EventBuilder
from synapse.federation.sender import FederationSender
from synapse.handlers.presence import (
    BUSY_ONLINE_TIMEOUT,
    EXTERNAL_PROCESS_EXPIRY,
    FEDERATION_PING_INTERVAL,
    FEDERATION_TIMEOUT,
    IDLE_TIMER,
    LAST_ACTIVE_GRANULARITY,
    SYNC_ONLINE_TIMEOUT,
    handle_timeout,
    handle_update,
)
from synapse.rest import admin
from synapse.rest.client import room
from synapse.server import HomeServer
from synapse.storage.database import LoggingDatabaseConnection
from synapse.types import JsonDict, UserID, get_domain_from_id
from synapse.util import Clock

from tests import unittest
from tests.replication._base import BaseMultiWorkerStreamTestCase


class PresenceUpdateTestCase(unittest.HomeserverTestCase):
    servlets = [admin.register_servlets]

    def prepare(
        self, reactor: MemoryReactor, clock: Clock, homeserver: HomeServer
    ) -> None:
        self.store = homeserver.get_datastores().main

    def test_offline_to_online(self) -> None:
        wheel_timer = Mock()
        user_id = "@foo:bar"
        now = 5000000

        prev_state = UserPresenceState.default(user_id)
        new_state = prev_state.copy_and_replace(
            state=PresenceState.ONLINE, last_active_ts=now
        )

        state, persist_and_notify, federation_ping = handle_update(
            prev_state, new_state, is_mine=True, wheel_timer=wheel_timer, now=now
        )

        self.assertTrue(persist_and_notify)
        self.assertTrue(state.currently_active)
        self.assertEqual(new_state.state, state.state)
        self.assertEqual(new_state.status_msg, state.status_msg)
        self.assertEqual(state.last_federation_update_ts, now)

        self.assertEqual(wheel_timer.insert.call_count, 3)
        wheel_timer.insert.assert_has_calls(
            [
                call(now=now, obj=user_id, then=new_state.last_active_ts + IDLE_TIMER),
                call(
                    now=now,
                    obj=user_id,
                    then=new_state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT,
                ),
                call(
                    now=now,
                    obj=user_id,
                    then=new_state.last_active_ts + LAST_ACTIVE_GRANULARITY,
                ),
            ],
            any_order=True,
        )

    def test_online_to_online(self) -> None:
        wheel_timer = Mock()
        user_id = "@foo:bar"
        now = 5000000

        prev_state = UserPresenceState.default(user_id)
        prev_state = prev_state.copy_and_replace(
            state=PresenceState.ONLINE, last_active_ts=now, currently_active=True
        )

        new_state = prev_state.copy_and_replace(
            state=PresenceState.ONLINE, last_active_ts=now
        )

        state, persist_and_notify, federation_ping = handle_update(
            prev_state, new_state, is_mine=True, wheel_timer=wheel_timer, now=now
        )

        self.assertFalse(persist_and_notify)
        self.assertTrue(federation_ping)
        self.assertTrue(state.currently_active)
        self.assertEqual(new_state.state, state.state)
        self.assertEqual(new_state.status_msg, state.status_msg)
        self.assertEqual(state.last_federation_update_ts, now)

        self.assertEqual(wheel_timer.insert.call_count, 3)
        wheel_timer.insert.assert_has_calls(
            [
                call(now=now, obj=user_id, then=new_state.last_active_ts + IDLE_TIMER),
                call(
                    now=now,
                    obj=user_id,
                    then=new_state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT,
                ),
                call(
                    now=now,
                    obj=user_id,
                    then=new_state.last_active_ts + LAST_ACTIVE_GRANULARITY,
                ),
            ],
            any_order=True,
        )

    def test_online_to_online_last_active_noop(self) -> None:
        wheel_timer = Mock()
        user_id = "@foo:bar"
        now = 5000000

        prev_state = UserPresenceState.default(user_id)
        prev_state = prev_state.copy_and_replace(
            state=PresenceState.ONLINE,
            last_active_ts=now - LAST_ACTIVE_GRANULARITY - 10,
            currently_active=True,
        )

        new_state = prev_state.copy_and_replace(
            state=PresenceState.ONLINE, last_active_ts=now
        )

        state, persist_and_notify, federation_ping = handle_update(
            prev_state, new_state, is_mine=True, wheel_timer=wheel_timer, now=now
        )

        self.assertFalse(persist_and_notify)
        self.assertTrue(federation_ping)
        self.assertTrue(state.currently_active)
        self.assertEqual(new_state.state, state.state)
        self.assertEqual(new_state.status_msg, state.status_msg)
        self.assertEqual(state.last_federation_update_ts, now)

        self.assertEqual(wheel_timer.insert.call_count, 3)
        wheel_timer.insert.assert_has_calls(
            [
                call(now=now, obj=user_id, then=new_state.last_active_ts + IDLE_TIMER),
                call(
                    now=now,
                    obj=user_id,
                    then=new_state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT,
                ),
                call(
                    now=now,
                    obj=user_id,
                    then=new_state.last_active_ts + LAST_ACTIVE_GRANULARITY,
                ),
            ],
            any_order=True,
        )

    def test_online_to_online_last_active(self) -> None:
        wheel_timer = Mock()
        user_id = "@foo:bar"
        now = 5000000

        prev_state = UserPresenceState.default(user_id)
        prev_state = prev_state.copy_and_replace(
            state=PresenceState.ONLINE,
            last_active_ts=now - LAST_ACTIVE_GRANULARITY - 1,
            currently_active=True,
        )

        new_state = prev_state.copy_and_replace(state=PresenceState.ONLINE)

        state, persist_and_notify, federation_ping = handle_update(
            prev_state, new_state, is_mine=True, wheel_timer=wheel_timer, now=now
        )

        self.assertTrue(persist_and_notify)
        self.assertFalse(state.currently_active)
        self.assertEqual(new_state.state, state.state)
        self.assertEqual(new_state.status_msg, state.status_msg)
        self.assertEqual(state.last_federation_update_ts, now)

        self.assertEqual(wheel_timer.insert.call_count, 2)
        wheel_timer.insert.assert_has_calls(
            [
                call(now=now, obj=user_id, then=new_state.last_active_ts + IDLE_TIMER),
                call(
                    now=now,
                    obj=user_id,
                    then=new_state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT,
                ),
            ],
            any_order=True,
        )

    def test_remote_ping_timer(self) -> None:
        wheel_timer = Mock()
        user_id = "@foo:bar"
        now = 5000000

        prev_state = UserPresenceState.default(user_id)
        prev_state = prev_state.copy_and_replace(
            state=PresenceState.ONLINE, last_active_ts=now
        )

        new_state = prev_state.copy_and_replace(state=PresenceState.ONLINE)

        state, persist_and_notify, federation_ping = handle_update(
            prev_state, new_state, is_mine=False, wheel_timer=wheel_timer, now=now
        )

        self.assertFalse(persist_and_notify)
        self.assertFalse(federation_ping)
        self.assertFalse(state.currently_active)
        self.assertEqual(new_state.state, state.state)
        self.assertEqual(new_state.status_msg, state.status_msg)

        self.assertEqual(wheel_timer.insert.call_count, 1)
        wheel_timer.insert.assert_has_calls(
            [
                call(
                    now=now,
                    obj=user_id,
                    then=new_state.last_federation_update_ts + FEDERATION_TIMEOUT,
                )
            ],
            any_order=True,
        )

    def test_online_to_offline(self) -> None:
        wheel_timer = Mock()
        user_id = "@foo:bar"
        now = 5000000

        prev_state = UserPresenceState.default(user_id)
        prev_state = prev_state.copy_and_replace(
            state=PresenceState.ONLINE, last_active_ts=now, currently_active=True
        )

        new_state = prev_state.copy_and_replace(state=PresenceState.OFFLINE)

        state, persist_and_notify, federation_ping = handle_update(
            prev_state, new_state, is_mine=True, wheel_timer=wheel_timer, now=now
        )

        self.assertTrue(persist_and_notify)
        self.assertEqual(new_state.state, state.state)
        self.assertEqual(state.last_federation_update_ts, now)

        self.assertEqual(wheel_timer.insert.call_count, 0)

    def test_online_to_idle(self) -> None:
        wheel_timer = Mock()
        user_id = "@foo:bar"
        now = 5000000

        prev_state = UserPresenceState.default(user_id)
        prev_state = prev_state.copy_and_replace(
            state=PresenceState.ONLINE, last_active_ts=now, currently_active=True
        )

        new_state = prev_state.copy_and_replace(state=PresenceState.UNAVAILABLE)

        state, persist_and_notify, federation_ping = handle_update(
            prev_state, new_state, is_mine=True, wheel_timer=wheel_timer, now=now
        )

        self.assertTrue(persist_and_notify)
        self.assertEqual(new_state.state, state.state)
        self.assertEqual(state.last_federation_update_ts, now)
        self.assertEqual(new_state.state, state.state)
        self.assertEqual(new_state.status_msg, state.status_msg)

        self.assertEqual(wheel_timer.insert.call_count, 1)
        wheel_timer.insert.assert_has_calls(
            [
                call(
                    now=now,
                    obj=user_id,
                    then=new_state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT,
                )
            ],
            any_order=True,
        )

    def test_persisting_presence_updates(self) -> None:
        """Tests that the latest presence state for each user is persisted correctly"""
        # Create some test users and presence states for them
        presence_states = []
        for i in range(5):
            user_id = self.register_user(f"user_{i}", "password")

            presence_state = UserPresenceState(
                user_id=user_id,
                state="online",
                last_active_ts=1,
                last_federation_update_ts=1,
                last_user_sync_ts=1,
                status_msg="I'm online!",
                currently_active=True,
            )
            presence_states.append(presence_state)

        # Persist these presence updates to the database
        self.get_success(self.store.update_presence(presence_states))

        # Check that each update is present in the database
        db_presence_states_raw = self.get_success(
            self.store.get_all_presence_updates(
                instance_name="master",
                last_id=0,
                current_id=len(presence_states) + 1,
                limit=len(presence_states),
            )
        )

        # Extract presence update user ID and state information into lists of tuples
        db_presence_states = [(ps[0], ps[1]) for _, ps in db_presence_states_raw[0]]
        presence_states_compare = [(ps.user_id, ps.state) for ps in presence_states]

        # Compare what we put into the storage with what we got out.
        # They should be identical.
        self.assertEqual(presence_states_compare, db_presence_states)


class PresenceTimeoutTestCase(unittest.TestCase):
    """Tests different timers and that the timer does not change `status_msg` of user."""

    def test_idle_timer(self) -> None:
        user_id = "@foo:bar"
        device_id = "dev-1"
        status_msg = "I'm here!"
        now = 5000000

        state = UserPresenceState.default(user_id)
        state = state.copy_and_replace(
            state=PresenceState.ONLINE,
            last_active_ts=now - IDLE_TIMER - 1,
            last_user_sync_ts=now,
            status_msg=status_msg,
        )
        device_state = UserDevicePresenceState(
            user_id=user_id,
            device_id=device_id,
            state=state.state,
            last_active_ts=state.last_active_ts,
            last_sync_ts=state.last_user_sync_ts,
        )

        new_state = handle_timeout(
            state,
            is_mine=True,
            syncing_device_ids=set(),
            user_devices={device_id: device_state},
            now=now,
        )

        self.assertIsNotNone(new_state)
        assert new_state is not None
        self.assertEqual(new_state.state, PresenceState.UNAVAILABLE)
        self.assertEqual(new_state.status_msg, status_msg)

    def test_busy_no_idle(self) -> None:
        """
        Tests that a user setting their presence to busy but idling doesn't turn their
        presence state into unavailable.
        """
        user_id = "@foo:bar"
        device_id = "dev-1"
        status_msg = "I'm here!"
        now = 5000000

        state = UserPresenceState.default(user_id)
        state = state.copy_and_replace(
            state=PresenceState.BUSY,
            last_active_ts=now - IDLE_TIMER - 1,
            last_user_sync_ts=now,
            status_msg=status_msg,
        )
        device_state = UserDevicePresenceState(
            user_id=user_id,
            device_id=device_id,
            state=state.state,
            last_active_ts=state.last_active_ts,
            last_sync_ts=state.last_user_sync_ts,
        )

        new_state = handle_timeout(
            state,
            is_mine=True,
            syncing_device_ids=set(),
            user_devices={device_id: device_state},
            now=now,
        )

        self.assertIsNotNone(new_state)
        assert new_state is not None
        self.assertEqual(new_state.state, PresenceState.BUSY)
        self.assertEqual(new_state.status_msg, status_msg)

    def test_sync_timeout(self) -> None:
        user_id = "@foo:bar"
        device_id = "dev-1"
        status_msg = "I'm here!"
        now = 5000000

        state = UserPresenceState.default(user_id)
        state = state.copy_and_replace(
            state=PresenceState.ONLINE,
            last_active_ts=0,
            last_user_sync_ts=now - SYNC_ONLINE_TIMEOUT - 1,
            status_msg=status_msg,
        )
        device_state = UserDevicePresenceState(
            user_id=user_id,
            device_id=device_id,
            state=state.state,
            last_active_ts=state.last_active_ts,
            last_sync_ts=state.last_user_sync_ts,
        )

        new_state = handle_timeout(
            state,
            is_mine=True,
            syncing_device_ids=set(),
            user_devices={device_id: device_state},
            now=now,
        )

        self.assertIsNotNone(new_state)
        assert new_state is not None
        self.assertEqual(new_state.state, PresenceState.OFFLINE)
        self.assertEqual(new_state.status_msg, status_msg)

    def test_sync_online(self) -> None:
        user_id = "@foo:bar"
        device_id = "dev-1"
        status_msg = "I'm here!"
        now = 5000000

        state = UserPresenceState.default(user_id)
        state = state.copy_and_replace(
            state=PresenceState.ONLINE,
            last_active_ts=now - SYNC_ONLINE_TIMEOUT - 1,
            last_user_sync_ts=now - SYNC_ONLINE_TIMEOUT - 1,
            status_msg=status_msg,
        )
        device_state = UserDevicePresenceState(
            user_id=user_id,
            device_id=device_id,
            state=state.state,
            last_active_ts=state.last_active_ts,
            last_sync_ts=state.last_user_sync_ts,
        )

        new_state = handle_timeout(
            state,
            is_mine=True,
            syncing_device_ids={(user_id, device_id)},
            user_devices={device_id: device_state},
            now=now,
        )

        self.assertIsNotNone(new_state)
        assert new_state is not None
        self.assertEqual(new_state.state, PresenceState.ONLINE)
        self.assertEqual(new_state.status_msg, status_msg)

    def test_federation_ping(self) -> None:
        user_id = "@foo:bar"
        device_id = "dev-1"
        status_msg = "I'm here!"
        now = 5000000

        state = UserPresenceState.default(user_id)
        state = state.copy_and_replace(
            state=PresenceState.ONLINE,
            last_active_ts=now,
            last_user_sync_ts=now,
            last_federation_update_ts=now - FEDERATION_PING_INTERVAL - 1,
            status_msg=status_msg,
        )
        device_state = UserDevicePresenceState(
            user_id=user_id,
            device_id=device_id,
            state=state.state,
            last_active_ts=state.last_active_ts,
            last_sync_ts=state.last_user_sync_ts,
        )

        new_state = handle_timeout(
            state,
            is_mine=True,
            syncing_device_ids=set(),
            user_devices={device_id: device_state},
            now=now,
        )

        self.assertIsNotNone(new_state)
        self.assertEqual(state, new_state)

    def test_no_timeout(self) -> None:
        user_id = "@foo:bar"
        device_id = "dev-1"
        now = 5000000

        state = UserPresenceState.default(user_id)
        state = state.copy_and_replace(
            state=PresenceState.ONLINE,
            last_active_ts=now,
            last_user_sync_ts=now,
            last_federation_update_ts=now,
        )
        device_state = UserDevicePresenceState(
            user_id=user_id,
            device_id=device_id,
            state=state.state,
            last_active_ts=state.last_active_ts,
            last_sync_ts=state.last_user_sync_ts,
        )

        new_state = handle_timeout(
            state,
            is_mine=True,
            syncing_device_ids=set(),
            user_devices={device_id: device_state},
            now=now,
        )

        self.assertIsNone(new_state)

    def test_federation_timeout(self) -> None:
        user_id = "@foo:bar"
        status_msg = "I'm here!"
        now = 5000000

        state = UserPresenceState.default(user_id)
        state = state.copy_and_replace(
            state=PresenceState.ONLINE,
            last_active_ts=now,
            last_user_sync_ts=now,
            last_federation_update_ts=now - FEDERATION_TIMEOUT - 1,
            status_msg=status_msg,
        )

        # Note that this is a remote user so we do not have their device information.
        new_state = handle_timeout(
            state, is_mine=False, syncing_device_ids=set(), user_devices={}, now=now
        )

        self.assertIsNotNone(new_state)
        assert new_state is not None
        self.assertEqual(new_state.state, PresenceState.OFFLINE)
        self.assertEqual(new_state.status_msg, status_msg)

    def test_last_active(self) -> None:
        user_id = "@foo:bar"
        device_id = "dev-1"
        status_msg = "I'm here!"
        now = 5000000

        state = UserPresenceState.default(user_id)
        state = state.copy_and_replace(
            state=PresenceState.ONLINE,
            last_active_ts=now - LAST_ACTIVE_GRANULARITY - 1,
            last_user_sync_ts=now,
            last_federation_update_ts=now,
            status_msg=status_msg,
        )
        device_state = UserDevicePresenceState(
            user_id=user_id,
            device_id=device_id,
            state=state.state,
            last_active_ts=state.last_active_ts,
            last_sync_ts=state.last_user_sync_ts,
        )

        new_state = handle_timeout(
            state,
            is_mine=True,
            syncing_device_ids=set(),
            user_devices={device_id: device_state},
            now=now,
        )

        self.assertIsNotNone(new_state)
        self.assertEqual(state, new_state)


class PresenceHandlerInitTestCase(unittest.HomeserverTestCase):
    def default_config(self) -> JsonDict:
        config = super().default_config()
        # Disable background tasks on this worker so that the PresenceHandler isn't
        # loaded until we request it.
        config["run_background_tasks_on"] = "other"
        return config

    def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
        self.user_id = f"@test:{self.hs.config.server.server_name}"
        self.device_id = "dev-1"

        # Move the reactor to the initial time.
        self.reactor.advance(1000)
        now = self.clock.time_msec()

        main_store = hs.get_datastores().main
        self.get_success(
            main_store.update_presence(
                [
                    UserPresenceState(
                        user_id=self.user_id,
                        state=PresenceState.ONLINE,
                        last_active_ts=now,
                        last_federation_update_ts=now,
                        last_user_sync_ts=now,
                        status_msg=None,
                        currently_active=True,
                    )
                ]
            )
        )

        # Regenerate the preloaded presence information on PresenceStore.
        def refill_presence(db_conn: LoggingDatabaseConnection) -> None:
            main_store._presence_on_startup = main_store._get_active_presence(db_conn)

        self.get_success(main_store.db_pool.runWithConnection(refill_presence))

    def test_restored_presence_idles(self) -> None:
        """The presence state restored from the database should not persist forever."""

        # Get the handler (which kicks off a bunch of timers).
        presence_handler = self.hs.get_presence_handler()

        # Assert the user is online.
        state = self.get_success(
            presence_handler.get_state(UserID.from_string(self.user_id))
        )
        self.assertEqual(state.state, PresenceState.ONLINE)

        # Advance such that the user should timeout.
        self.reactor.advance(SYNC_ONLINE_TIMEOUT / 1000)
        self.reactor.pump([5])

        # Check that the user is now offline.
        state = self.get_success(
            presence_handler.get_state(UserID.from_string(self.user_id))
        )
        self.assertEqual(state.state, PresenceState.OFFLINE)

    @parameterized.expand(
        [
            (PresenceState.BUSY, PresenceState.BUSY),
            (PresenceState.ONLINE, PresenceState.ONLINE),
            (PresenceState.UNAVAILABLE, PresenceState.ONLINE),
            # Offline syncs don't update the state.
            (PresenceState.OFFLINE, PresenceState.ONLINE),
        ]
    )
    @unittest.override_config({"experimental_features": {"msc3026_enabled": True}})
    def test_restored_presence_online_after_sync(
        self, sync_state: str, expected_state: str
    ) -> None:
        """
        The presence state restored from the database should be overridden with sync after a timeout.

        Args:
            sync_state: The presence state of the new sync.
            expected_state: The expected presence right after the sync.
        """

        # Get the handler (which kicks off a bunch of timers).
        presence_handler = self.hs.get_presence_handler()

        # Assert the user is online, as restored.
        state = self.get_success(
            presence_handler.get_state(UserID.from_string(self.user_id))
        )
        self.assertEqual(state.state, PresenceState.ONLINE)

        # Advance slightly and sync.
        self.reactor.advance(SYNC_ONLINE_TIMEOUT / 1000 / 2)
        self.get_success(
            presence_handler.user_syncing(
                self.user_id,
                self.device_id,
                sync_state != PresenceState.OFFLINE,
                sync_state,
            )
        )

        # Assert the user is in the expected state.
        state = self.get_success(
            presence_handler.get_state(UserID.from_string(self.user_id))
        )
        self.assertEqual(state.state, expected_state)

        # Advance such that the user's preloaded data times out, but not the new sync.
        self.reactor.advance(SYNC_ONLINE_TIMEOUT / 1000 / 2)
        self.reactor.pump([5])

        # Check that the user is in the sync state (as the client is currently syncing still).
        state = self.get_success(
            presence_handler.get_state(UserID.from_string(self.user_id))
        )
        self.assertEqual(state.state, sync_state)


class PresenceHandlerTestCase(BaseMultiWorkerStreamTestCase):
    user_id = "@test:server"
    user_id_obj = UserID.from_string(user_id)
    device_id = "dev-1"

    def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
        self.presence_handler = hs.get_presence_handler()
        self.clock = hs.get_clock()

    def test_external_process_timeout(self) -> None:
        """Test that if an external process doesn't update the records for a while
        we time out their syncing users presence.
        """

        # Create a worker and use it to handle /sync traffic instead.
        # This is used to test that presence changes get replicated from workers
        # to the main process correctly.
        worker_to_sync_against = self.make_worker_hs(
            "synapse.app.generic_worker", {"worker_name": "synchrotron"}
        )
        worker_presence_handler = worker_to_sync_against.get_presence_handler()

        self.get_success(
            worker_presence_handler.user_syncing(
                self.user_id, self.device_id, True, PresenceState.ONLINE
            ),
            by=0.1,
        )

        # Check that if we wait a while without telling the handler the user has
        # stopped syncing that their presence state doesn't get timed out.
        self.reactor.advance(EXTERNAL_PROCESS_EXPIRY / 2)

        state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
        self.assertEqual(state.state, PresenceState.ONLINE)

        # Check that if the external process timeout fires, then the syncing
        # user gets timed out
        self.reactor.advance(EXTERNAL_PROCESS_EXPIRY)

        state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
        self.assertEqual(state.state, PresenceState.OFFLINE)

    def test_user_goes_offline_by_timeout_status_msg_remain(self) -> None:
        """Test that if a user doesn't update the records for a while
        users presence goes `OFFLINE` because of timeout and `status_msg` remains.
        """
        status_msg = "I'm here!"

        # Mark user as online
        self._set_presencestate_with_status_msg(PresenceState.ONLINE, status_msg)

        # Check that if we wait a while without telling the handler the user has
        # stopped syncing that their presence state doesn't get timed out.
        self.reactor.advance(SYNC_ONLINE_TIMEOUT / 2)

        state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
        self.assertEqual(state.state, PresenceState.ONLINE)
        self.assertEqual(state.status_msg, status_msg)

        # Check that if the timeout fires, then the syncing user gets timed out
        self.reactor.advance(SYNC_ONLINE_TIMEOUT)

        state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
        # status_msg should remain even after going offline
        self.assertEqual(state.state, PresenceState.OFFLINE)
        self.assertEqual(state.status_msg, status_msg)

    def test_user_goes_offline_manually_with_no_status_msg(self) -> None:
        """Test that if a user change presence manually to `OFFLINE`
        and no status is set, that `status_msg` is `None`.
        """
        status_msg = "I'm here!"

        # Mark user as online
        self._set_presencestate_with_status_msg(PresenceState.ONLINE, status_msg)

        # Mark user as offline
        self.get_success(
            self.presence_handler.set_state(
                self.user_id_obj, self.device_id, {"presence": PresenceState.OFFLINE}
            )
        )

        state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
        self.assertEqual(state.state, PresenceState.OFFLINE)
        self.assertEqual(state.status_msg, None)

    def test_user_goes_offline_manually_with_status_msg(self) -> None:
        """Test that if a user change presence manually to `OFFLINE`
        and a status is set, that `status_msg` appears.
        """
        status_msg = "I'm here!"

        # Mark user as online
        self._set_presencestate_with_status_msg(PresenceState.ONLINE, status_msg)

        # Mark user as offline
        self._set_presencestate_with_status_msg(PresenceState.OFFLINE, "And now here.")

    def test_user_reset_online_with_no_status(self) -> None:
        """Test that if a user set again the presence manually
        and no status is set, that `status_msg` is `None`.
        """
        status_msg = "I'm here!"

        # Mark user as online
        self._set_presencestate_with_status_msg(PresenceState.ONLINE, status_msg)

        # Mark user as online again
        self.get_success(
            self.presence_handler.set_state(
                self.user_id_obj, self.device_id, {"presence": PresenceState.ONLINE}
            )
        )

        state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
        # status_msg should remain even after going offline
        self.assertEqual(state.state, PresenceState.ONLINE)
        self.assertEqual(state.status_msg, None)

    def test_set_presence_with_status_msg_none(self) -> None:
        """Test that if a user set again the presence manually
        and status is `None`, that `status_msg` is `None`.
        """
        status_msg = "I'm here!"

        # Mark user as online
        self._set_presencestate_with_status_msg(PresenceState.ONLINE, status_msg)

        # Mark user as online and `status_msg = None`
        self._set_presencestate_with_status_msg(PresenceState.ONLINE, None)

    def test_set_presence_from_syncing_not_set(self) -> None:
        """Test that presence is not set by syncing if affect_presence is false"""
        status_msg = "I'm here!"

        self._set_presencestate_with_status_msg(PresenceState.UNAVAILABLE, status_msg)

        self.get_success(
            self.presence_handler.user_syncing(
                self.user_id, self.device_id, False, PresenceState.ONLINE
            )
        )

        state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
        # we should still be unavailable
        self.assertEqual(state.state, PresenceState.UNAVAILABLE)
        # and status message should still be the same
        self.assertEqual(state.status_msg, status_msg)

    def test_set_presence_from_syncing_is_set(self) -> None:
        """Test that presence is set by syncing if affect_presence is true"""
        status_msg = "I'm here!"

        self._set_presencestate_with_status_msg(PresenceState.UNAVAILABLE, status_msg)

        self.get_success(
            self.presence_handler.user_syncing(
                self.user_id, self.device_id, True, PresenceState.ONLINE
            )
        )

        state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
        # we should now be online
        self.assertEqual(state.state, PresenceState.ONLINE)

    @parameterized.expand(
        # A list of tuples of 4 strings:
        #
        # * The presence state of device 1.
        # * The presence state of device 2.
        # * The expected user presence state after both devices have synced.
        # * The expected user presence state after device 1 has idled.
        # * The expected user presence state after device 2 has idled.
        # * True to use workers, False a monolith.
        [
            (*cases, workers)
            for workers in (False, True)
            for cases in [
                # If both devices have the same state, online should eventually idle.
                # Otherwise, the state doesn't change.
                (
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                ),
                (
                    PresenceState.ONLINE,
                    PresenceState.ONLINE,
                    PresenceState.ONLINE,
                    PresenceState.ONLINE,
                    PresenceState.UNAVAILABLE,
                ),
                (
                    PresenceState.UNAVAILABLE,
                    PresenceState.UNAVAILABLE,
                    PresenceState.UNAVAILABLE,
                    PresenceState.UNAVAILABLE,
                    PresenceState.UNAVAILABLE,
                ),
                (
                    PresenceState.OFFLINE,
                    PresenceState.OFFLINE,
                    PresenceState.OFFLINE,
                    PresenceState.OFFLINE,
                    PresenceState.OFFLINE,
                ),
                # If the second device has a "lower" state it should fallback to it,
                # except for "busy" which overrides.
                (
                    PresenceState.BUSY,
                    PresenceState.ONLINE,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                ),
                (
                    PresenceState.BUSY,
                    PresenceState.UNAVAILABLE,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                ),
                (
                    PresenceState.BUSY,
                    PresenceState.OFFLINE,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                ),
                (
                    PresenceState.ONLINE,
                    PresenceState.UNAVAILABLE,
                    PresenceState.ONLINE,
                    PresenceState.UNAVAILABLE,
                    PresenceState.UNAVAILABLE,
                ),
                (
                    PresenceState.ONLINE,
                    PresenceState.OFFLINE,
                    PresenceState.ONLINE,
                    PresenceState.UNAVAILABLE,
                    PresenceState.UNAVAILABLE,
                ),
                (
                    PresenceState.UNAVAILABLE,
                    PresenceState.OFFLINE,
                    PresenceState.UNAVAILABLE,
                    PresenceState.UNAVAILABLE,
                    PresenceState.UNAVAILABLE,
                ),
                # If the second device has a "higher" state it should override.
                (
                    PresenceState.ONLINE,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                ),
                (
                    PresenceState.UNAVAILABLE,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                ),
                (
                    PresenceState.OFFLINE,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                ),
                (
                    PresenceState.UNAVAILABLE,
                    PresenceState.ONLINE,
                    PresenceState.ONLINE,
                    PresenceState.ONLINE,
                    PresenceState.UNAVAILABLE,
                ),
                (
                    PresenceState.OFFLINE,
                    PresenceState.ONLINE,
                    PresenceState.ONLINE,
                    PresenceState.ONLINE,
                    PresenceState.UNAVAILABLE,
                ),
                (
                    PresenceState.OFFLINE,
                    PresenceState.UNAVAILABLE,
                    PresenceState.UNAVAILABLE,
                    PresenceState.UNAVAILABLE,
                    PresenceState.UNAVAILABLE,
                ),
            ]
        ],
        name_func=lambda testcase_func, param_num, params: f"{testcase_func.__name__}_{param_num}_{'workers' if params.args[5] else 'monolith'}",
    )
    @unittest.override_config({"experimental_features": {"msc3026_enabled": True}})
    def test_set_presence_from_syncing_multi_device(
        self,
        dev_1_state: str,
        dev_2_state: str,
        expected_state_1: str,
        expected_state_2: str,
        expected_state_3: str,
        test_with_workers: bool,
    ) -> None:
        """
        Test the behaviour of multiple devices syncing at the same time.

        Roughly the user's presence state should be set to the "highest" priority
        of all the devices. When a device then goes offline its state should be
        discarded and the next highest should win.

        Note that these tests use the idle timer (and don't close the syncs), it
        is unlikely that a *single* sync would last this long, but is close enough
        to continually syncing with that current state.
        """
        user_id = f"@test:{self.hs.config.server.server_name}"

        # By default, we call /sync against the main process.
        worker_presence_handler = self.presence_handler
        if test_with_workers:
            # Create a worker and use it to handle /sync traffic instead.
            # This is used to test that presence changes get replicated from workers
            # to the main process correctly.
            worker_to_sync_against = self.make_worker_hs(
                "synapse.app.generic_worker", {"worker_name": "synchrotron"}
            )
            worker_presence_handler = worker_to_sync_against.get_presence_handler()

        # 1. Sync with the first device.
        self.get_success(
            worker_presence_handler.user_syncing(
                user_id,
                "dev-1",
                affect_presence=dev_1_state != PresenceState.OFFLINE,
                presence_state=dev_1_state,
            ),
            by=0.01,
        )

        # 2. Wait half the idle timer.
        self.reactor.advance(IDLE_TIMER / 1000 / 2)
        self.reactor.pump([0.1])

        # 3. Sync with the second device.
        self.get_success(
            worker_presence_handler.user_syncing(
                user_id,
                "dev-2",
                affect_presence=dev_2_state != PresenceState.OFFLINE,
                presence_state=dev_2_state,
            ),
            by=0.01,
        )

        # 4. Assert the expected presence state.
        state = self.get_success(
            self.presence_handler.get_state(UserID.from_string(user_id))
        )
        self.assertEqual(state.state, expected_state_1)
        if test_with_workers:
            state = self.get_success(
                worker_presence_handler.get_state(UserID.from_string(user_id))
            )
            self.assertEqual(state.state, expected_state_1)

        # When testing with workers, make another random sync (with any *different*
        # user) to keep the process information from expiring.
        #
        # This is due to EXTERNAL_PROCESS_EXPIRY being equivalent to IDLE_TIMER.
        if test_with_workers:
            with self.get_success(
                worker_presence_handler.user_syncing(
                    f"@other-user:{self.hs.config.server.server_name}",
                    "dev-3",
                    affect_presence=True,
                    presence_state=PresenceState.ONLINE,
                ),
                by=0.01,
            ):
                pass

        # 5. Advance such that the first device should be discarded (the idle timer),
        # then pump so _handle_timeouts function to called.
        self.reactor.advance(IDLE_TIMER / 1000 / 2)
        self.reactor.pump([0.01])

        # 6. Assert the expected presence state.
        state = self.get_success(
            self.presence_handler.get_state(UserID.from_string(user_id))
        )
        self.assertEqual(state.state, expected_state_2)
        if test_with_workers:
            state = self.get_success(
                worker_presence_handler.get_state(UserID.from_string(user_id))
            )
            self.assertEqual(state.state, expected_state_2)

        # 7. Advance such that the second device should be discarded (half the idle timer),
        # then pump so _handle_timeouts function to called.
        self.reactor.advance(IDLE_TIMER / 1000 / 2)
        self.reactor.pump([0.1])

        # 8. The devices are still "syncing" (the sync context managers were never
        # closed), so might idle.
        state = self.get_success(
            self.presence_handler.get_state(UserID.from_string(user_id))
        )
        self.assertEqual(state.state, expected_state_3)
        if test_with_workers:
            state = self.get_success(
                worker_presence_handler.get_state(UserID.from_string(user_id))
            )
            self.assertEqual(state.state, expected_state_3)

    @parameterized.expand(
        # A list of tuples of 4 strings:
        #
        # * The presence state of device 1.
        # * The presence state of device 2.
        # * The expected user presence state after both devices have synced.
        # * The expected user presence state after device 1 has stopped syncing.
        # * True to use workers, False a monolith.
        [
            (*cases, workers)
            for workers in (False, True)
            for cases in [
                # If both devices have the same state, nothing exciting should happen.
                (
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                ),
                (
                    PresenceState.ONLINE,
                    PresenceState.ONLINE,
                    PresenceState.ONLINE,
                    PresenceState.ONLINE,
                ),
                (
                    PresenceState.UNAVAILABLE,
                    PresenceState.UNAVAILABLE,
                    PresenceState.UNAVAILABLE,
                    PresenceState.UNAVAILABLE,
                ),
                (
                    PresenceState.OFFLINE,
                    PresenceState.OFFLINE,
                    PresenceState.OFFLINE,
                    PresenceState.OFFLINE,
                ),
                # If the second device has a "lower" state it should fallback to it,
                # except for "busy" which overrides.
                (
                    PresenceState.BUSY,
                    PresenceState.ONLINE,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                ),
                (
                    PresenceState.BUSY,
                    PresenceState.UNAVAILABLE,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                ),
                (
                    PresenceState.BUSY,
                    PresenceState.OFFLINE,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                ),
                (
                    PresenceState.ONLINE,
                    PresenceState.UNAVAILABLE,
                    PresenceState.ONLINE,
                    PresenceState.UNAVAILABLE,
                ),
                (
                    PresenceState.ONLINE,
                    PresenceState.OFFLINE,
                    PresenceState.ONLINE,
                    PresenceState.OFFLINE,
                ),
                (
                    PresenceState.UNAVAILABLE,
                    PresenceState.OFFLINE,
                    PresenceState.UNAVAILABLE,
                    PresenceState.OFFLINE,
                ),
                # If the second device has a "higher" state it should override.
                (
                    PresenceState.ONLINE,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                ),
                (
                    PresenceState.UNAVAILABLE,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                ),
                (
                    PresenceState.OFFLINE,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                    PresenceState.BUSY,
                ),
                (
                    PresenceState.UNAVAILABLE,
                    PresenceState.ONLINE,
                    PresenceState.ONLINE,
                    PresenceState.ONLINE,
                ),
                (
                    PresenceState.OFFLINE,
                    PresenceState.ONLINE,
                    PresenceState.ONLINE,
                    PresenceState.ONLINE,
                ),
                (
                    PresenceState.OFFLINE,
                    PresenceState.UNAVAILABLE,
                    PresenceState.UNAVAILABLE,
                    PresenceState.UNAVAILABLE,
                ),
            ]
        ],
        name_func=lambda testcase_func, param_num, params: f"{testcase_func.__name__}_{param_num}_{'workers' if params.args[4] else 'monolith'}",
    )
    @unittest.override_config({"experimental_features": {"msc3026_enabled": True}})
    def test_set_presence_from_non_syncing_multi_device(
        self,
        dev_1_state: str,
        dev_2_state: str,
        expected_state_1: str,
        expected_state_2: str,
        test_with_workers: bool,
    ) -> None:
        """
        Test the behaviour of multiple devices syncing at the same time.

        Roughly the user's presence state should be set to the "highest" priority
        of all the devices. When a device then goes offline its state should be
        discarded and the next highest should win.

        Note that these tests use the idle timer (and don't close the syncs), it
        is unlikely that a *single* sync would last this long, but is close enough
        to continually syncing with that current state.
        """
        user_id = f"@test:{self.hs.config.server.server_name}"

        # By default, we call /sync against the main process.
        worker_presence_handler = self.presence_handler
        if test_with_workers:
            # Create a worker and use it to handle /sync traffic instead.
            # This is used to test that presence changes get replicated from workers
            # to the main process correctly.
            worker_to_sync_against = self.make_worker_hs(
                "synapse.app.generic_worker", {"worker_name": "synchrotron"}
            )
            worker_presence_handler = worker_to_sync_against.get_presence_handler()

        # 1. Sync with the first device.
        sync_1 = self.get_success(
            worker_presence_handler.user_syncing(
                user_id,
                "dev-1",
                affect_presence=dev_1_state != PresenceState.OFFLINE,
                presence_state=dev_1_state,
            ),
            by=0.1,
        )

        # 2. Sync with the second device.
        sync_2 = self.get_success(
            worker_presence_handler.user_syncing(
                user_id,
                "dev-2",
                affect_presence=dev_2_state != PresenceState.OFFLINE,
                presence_state=dev_2_state,
            ),
            by=0.1,
        )

        # 3. Assert the expected presence state.
        state = self.get_success(
            self.presence_handler.get_state(UserID.from_string(user_id))
        )
        self.assertEqual(state.state, expected_state_1)
        if test_with_workers:
            state = self.get_success(
                worker_presence_handler.get_state(UserID.from_string(user_id))
            )
            self.assertEqual(state.state, expected_state_1)

        # 4. Disconnect the first device.
        with sync_1:
            pass

        # 5. Advance such that the first device should be discarded (the sync timeout),
        # then pump so _handle_timeouts function to called.
        self.reactor.advance(SYNC_ONLINE_TIMEOUT / 1000)
        self.reactor.pump([5])

        # 6. Assert the expected presence state.
        state = self.get_success(
            self.presence_handler.get_state(UserID.from_string(user_id))
        )
        self.assertEqual(state.state, expected_state_2)
        if test_with_workers:
            state = self.get_success(
                worker_presence_handler.get_state(UserID.from_string(user_id))
            )
            self.assertEqual(state.state, expected_state_2)

        # 7. Disconnect the second device.
        with sync_2:
            pass

        # 8. Advance such that the second device should be discarded (the sync timeout),
        # then pump so _handle_timeouts function to called.
        if dev_1_state == PresenceState.BUSY or dev_2_state == PresenceState.BUSY:
            timeout = BUSY_ONLINE_TIMEOUT
        else:
            timeout = SYNC_ONLINE_TIMEOUT
        self.reactor.advance(timeout / 1000)
        self.reactor.pump([5])

        # 9. There are no more devices, should be offline.
        state = self.get_success(
            self.presence_handler.get_state(UserID.from_string(user_id))
        )
        self.assertEqual(state.state, PresenceState.OFFLINE)
        if test_with_workers:
            state = self.get_success(
                worker_presence_handler.get_state(UserID.from_string(user_id))
            )
            self.assertEqual(state.state, PresenceState.OFFLINE)

    def test_set_presence_from_syncing_keeps_status(self) -> None:
        """Test that presence set by syncing retains status message"""
        status_msg = "I'm here!"

        self._set_presencestate_with_status_msg(PresenceState.UNAVAILABLE, status_msg)

        self.get_success(
            self.presence_handler.user_syncing(
                self.user_id, self.device_id, True, PresenceState.ONLINE
            )
        )

        state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
        # our status message should be the same as it was before
        self.assertEqual(state.status_msg, status_msg)

    @parameterized.expand([(False,), (True,)])
    @unittest.override_config({"experimental_features": {"msc3026_enabled": True}})
    def test_set_presence_from_syncing_keeps_busy(
        self, test_with_workers: bool
    ) -> None:
        """Test that presence set by syncing doesn't affect busy status

        Args:
            test_with_workers: If True, check the presence state of the user by calling
                /sync against a worker, rather than the main process.
        """
        status_msg = "I'm busy!"

        # By default, we call /sync against the main process.
        worker_to_sync_against = self.hs
        if test_with_workers:
            # Create a worker and use it to handle /sync traffic instead.
            # This is used to test that presence changes get replicated from workers
            # to the main process correctly.
            worker_to_sync_against = self.make_worker_hs(
                "synapse.app.generic_worker", {"worker_name": "synchrotron"}
            )

        # Set presence to BUSY
        self._set_presencestate_with_status_msg(PresenceState.BUSY, status_msg)

        # Perform a sync with a presence state other than busy. This should NOT change
        # our presence status; we only change from busy if we explicitly set it via
        # /presence/*.
        self.get_success(
            worker_to_sync_against.get_presence_handler().user_syncing(
                self.user_id, self.device_id, True, PresenceState.ONLINE
            ),
            by=0.1,
        )

        # Check against the main process that the user's presence did not change.
        state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
        # we should still be busy
        self.assertEqual(state.state, PresenceState.BUSY)

        # Advance such that the device would be discarded if it was not busy,
        # then pump so _handle_timeouts function to called.
        self.reactor.advance(IDLE_TIMER / 1000)
        self.reactor.pump([5])

        # The account should still be busy.
        state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
        self.assertEqual(state.state, PresenceState.BUSY)

        # Ensure that a /presence call can set the user *off* busy.
        self._set_presencestate_with_status_msg(PresenceState.ONLINE, status_msg)

        state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
        self.assertEqual(state.state, PresenceState.ONLINE)

    def _set_presencestate_with_status_msg(
        self, state: str, status_msg: Optional[str]
    ) -> None:
        """Set a PresenceState and status_msg and check the result.

        Args:
            state: The new PresenceState.
            status_msg: Status message that is to be set.
        """
        self.get_success(
            self.presence_handler.set_state(
                self.user_id_obj,
                self.device_id,
                {"presence": state, "status_msg": status_msg},
            )
        )

        new_state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
        self.assertEqual(new_state.state, state)
        self.assertEqual(new_state.status_msg, status_msg)


class PresenceFederationQueueTestCase(unittest.HomeserverTestCase):
    def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
        self.presence_handler = hs.get_presence_handler()
        self.clock = hs.get_clock()
        self.instance_name = hs.get_instance_name()

        self.queue = self.presence_handler.get_federation_queue()

    def test_send_and_get(self) -> None:
        state1 = UserPresenceState.default("@user1:test")
        state2 = UserPresenceState.default("@user2:test")
        state3 = UserPresenceState.default("@user3:test")

        prev_token = self.queue.get_current_token(self.instance_name)

        self.get_success(
            self.queue.send_presence_to_destinations(
                (state1, state2), ("dest1", "dest2")
            )
        )
        self.get_success(
            self.queue.send_presence_to_destinations((state3,), ("dest3",))
        )

        now_token = self.queue.get_current_token(self.instance_name)

        rows, upto_token, limited = self.get_success(
            self.queue.get_replication_rows("master", prev_token, now_token, 10)
        )

        self.assertEqual(upto_token, now_token)
        self.assertFalse(limited)

        expected_rows = [
            (1, ("dest1", "@user1:test")),
            (1, ("dest2", "@user1:test")),
            (1, ("dest1", "@user2:test")),
            (1, ("dest2", "@user2:test")),
            (2, ("dest3", "@user3:test")),
        ]

        self.assertCountEqual(rows, expected_rows)

        now_token = self.queue.get_current_token(self.instance_name)
        rows, upto_token, limited = self.get_success(
            self.queue.get_replication_rows("master", upto_token, now_token, 10)
        )
        self.assertEqual(upto_token, now_token)
        self.assertFalse(limited)
        self.assertCountEqual(rows, [])

    def test_send_and_get_split(self) -> None:
        state1 = UserPresenceState.default("@user1:test")
        state2 = UserPresenceState.default("@user2:test")
        state3 = UserPresenceState.default("@user3:test")

        prev_token = self.queue.get_current_token(self.instance_name)

        self.get_success(
            self.queue.send_presence_to_destinations(
                (state1, state2), ("dest1", "dest2")
            )
        )

        now_token = self.queue.get_current_token(self.instance_name)

        self.get_success(
            self.queue.send_presence_to_destinations((state3,), ("dest3",))
        )

        rows, upto_token, limited = self.get_success(
            self.queue.get_replication_rows("master", prev_token, now_token, 10)
        )

        self.assertEqual(upto_token, now_token)
        self.assertFalse(limited)

        expected_rows = [
            (1, ("dest1", "@user1:test")),
            (1, ("dest2", "@user1:test")),
            (1, ("dest1", "@user2:test")),
            (1, ("dest2", "@user2:test")),
        ]

        self.assertCountEqual(rows, expected_rows)

        now_token = self.queue.get_current_token(self.instance_name)
        rows, upto_token, limited = self.get_success(
            self.queue.get_replication_rows("master", upto_token, now_token, 10)
        )

        self.assertEqual(upto_token, now_token)
        self.assertFalse(limited)

        expected_rows = [
            (2, ("dest3", "@user3:test")),
        ]

        self.assertCountEqual(rows, expected_rows)

    def test_clear_queue_all(self) -> None:
        state1 = UserPresenceState.default("@user1:test")
        state2 = UserPresenceState.default("@user2:test")
        state3 = UserPresenceState.default("@user3:test")

        prev_token = self.queue.get_current_token(self.instance_name)

        self.get_success(
            self.queue.send_presence_to_destinations(
                (state1, state2), ("dest1", "dest2")
            )
        )
        self.get_success(
            self.queue.send_presence_to_destinations((state3,), ("dest3",))
        )

        self.reactor.advance(10 * 60 * 1000)

        now_token = self.queue.get_current_token(self.instance_name)

        rows, upto_token, limited = self.get_success(
            self.queue.get_replication_rows("master", prev_token, now_token, 10)
        )
        self.assertEqual(upto_token, now_token)
        self.assertFalse(limited)
        self.assertCountEqual(rows, [])

        prev_token = self.queue.get_current_token(self.instance_name)

        self.get_success(
            self.queue.send_presence_to_destinations(
                (state1, state2), ("dest1", "dest2")
            )
        )
        self.get_success(
            self.queue.send_presence_to_destinations((state3,), ("dest3",))
        )

        now_token = self.queue.get_current_token(self.instance_name)

        rows, upto_token, limited = self.get_success(
            self.queue.get_replication_rows("master", prev_token, now_token, 10)
        )
        self.assertEqual(upto_token, now_token)
        self.assertFalse(limited)

        expected_rows = [
            (3, ("dest1", "@user1:test")),
            (3, ("dest2", "@user1:test")),
            (3, ("dest1", "@user2:test")),
            (3, ("dest2", "@user2:test")),
            (4, ("dest3", "@user3:test")),
        ]

        self.assertCountEqual(rows, expected_rows)

    def test_partially_clear_queue(self) -> None:
        state1 = UserPresenceState.default("@user1:test")
        state2 = UserPresenceState.default("@user2:test")
        state3 = UserPresenceState.default("@user3:test")

        prev_token = self.queue.get_current_token(self.instance_name)

        self.get_success(
            self.queue.send_presence_to_destinations(
                (state1, state2), ("dest1", "dest2")
            )
        )

        self.reactor.advance(2 * 60 * 1000)

        self.get_success(
            self.queue.send_presence_to_destinations((state3,), ("dest3",))
        )

        self.reactor.advance(4 * 60 * 1000)

        now_token = self.queue.get_current_token(self.instance_name)

        rows, upto_token, limited = self.get_success(
            self.queue.get_replication_rows("master", prev_token, now_token, 10)
        )
        self.assertEqual(upto_token, now_token)
        self.assertFalse(limited)

        self.assertCountEqual(rows, [])

        prev_token = self.queue.get_current_token(self.instance_name)

        self.get_success(
            self.queue.send_presence_to_destinations(
                (state1, state2), ("dest1", "dest2")
            )
        )
        self.get_success(
            self.queue.send_presence_to_destinations((state3,), ("dest3",))
        )

        now_token = self.queue.get_current_token(self.instance_name)

        rows, upto_token, limited = self.get_success(
            self.queue.get_replication_rows("master", prev_token, now_token, 10)
        )
        self.assertEqual(upto_token, now_token)
        self.assertFalse(limited)

        expected_rows = [
            (3, ("dest1", "@user1:test")),
            (3, ("dest2", "@user1:test")),
            (3, ("dest1", "@user2:test")),
            (3, ("dest2", "@user2:test")),
            (4, ("dest3", "@user3:test")),
        ]

        self.assertCountEqual(rows, expected_rows)


class PresenceJoinTestCase(unittest.HomeserverTestCase):
    """Tests remote servers get told about presence of users in the room when
    they join and when new local users join.
    """

    user_id = "@test:server"

    servlets = [room.register_servlets]

    def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
        hs = self.setup_test_homeserver(
            "server",
            federation_sender=Mock(spec=FederationSender),
        )
        return hs

    def default_config(self) -> JsonDict:
        config = super().default_config()
        # Enable federation sending on the main process.
        config["federation_sender_instances"] = None
        return config

    def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
        self.federation_sender = cast(Mock, hs.get_federation_sender())
        self.event_builder_factory = hs.get_event_builder_factory()
        self.federation_event_handler = hs.get_federation_event_handler()
        self.presence_handler = hs.get_presence_handler()

        # self.event_builder_for_2 = EventBuilderFactory(hs)
        # self.event_builder_for_2.hostname = "test2"

        self.store = hs.get_datastores().main
        self.state = hs.get_state_handler()
        self._event_auth_handler = hs.get_event_auth_handler()

        # We don't actually check signatures in tests, so lets just create a
        # random key to use.
        self.random_signing_key = generate_signing_key("ver")

    def test_remote_joins(self) -> None:
        # We advance time to something that isn't 0, as we use 0 as a special
        # value.
        self.reactor.advance(1000000000000)

        # Create a room with two local users
        room_id = self.helper.create_room_as(self.user_id)
        self.helper.join(room_id, "@test2:server")

        # Mark test2 as online, test will be offline with a last_active of 0
        self.get_success(
            self.presence_handler.set_state(
                UserID.from_string("@test2:server"),
                "dev-1",
                {"presence": PresenceState.ONLINE},
            )
        )
        self.reactor.pump([0])  # Wait for presence updates to be handled

        #
        # Test that a new server gets told about existing presence
        #

        self.federation_sender.reset_mock()

        # Add a new remote server to the room
        self._add_new_user(room_id, "@alice:server2")

        # When new server is joined we send it the local users presence states.
        # We expect to only see user @test2:server, as @test:server is offline
        # and has a zero last_active_ts
        expected_state = self.get_success(
            self.presence_handler.current_state_for_user("@test2:server")
        )
        self.assertEqual(expected_state.state, PresenceState.ONLINE)
        self.federation_sender.send_presence_to_destinations.assert_called_once_with(
            destinations={"server2"}, states=[expected_state]
        )

        #
        # Test that only the new server gets sent presence and not existing servers
        #

        self.federation_sender.reset_mock()
        self._add_new_user(room_id, "@bob:server3")

        self.federation_sender.send_presence_to_destinations.assert_called_once_with(
            destinations={"server3"}, states=[expected_state]
        )

    def test_remote_gets_presence_when_local_user_joins(self) -> None:
        # We advance time to something that isn't 0, as we use 0 as a special
        # value.
        self.reactor.advance(1000000000000)

        # Create a room with one local users
        room_id = self.helper.create_room_as(self.user_id)

        # Mark test as online
        self.get_success(
            self.presence_handler.set_state(
                UserID.from_string("@test:server"),
                "dev-1",
                {"presence": PresenceState.ONLINE},
            )
        )

        # Mark test2 as online, test will be offline with a last_active of 0.
        # Note we don't join them to the room yet
        self.get_success(
            self.presence_handler.set_state(
                UserID.from_string("@test2:server"),
                "dev-1",
                {"presence": PresenceState.ONLINE},
            )
        )

        # Add servers to the room
        self._add_new_user(room_id, "@alice:server2")
        self._add_new_user(room_id, "@bob:server3")

        self.reactor.pump([0])  # Wait for presence updates to be handled

        #
        # Test that when a local join happens remote servers get told about it
        #

        self.federation_sender.reset_mock()

        # Join local user to room
        self.helper.join(room_id, "@test2:server")

        self.reactor.pump([0])  # Wait for presence updates to be handled

        # We expect to only send test2 presence to server2 and server3
        expected_state = self.get_success(
            self.presence_handler.current_state_for_user("@test2:server")
        )
        self.assertEqual(expected_state.state, PresenceState.ONLINE)
        self.federation_sender.send_presence_to_destinations.assert_called_once_with(
            destinations={"server2", "server3"}, states=[expected_state]
        )

    def _add_new_user(self, room_id: str, user_id: str) -> None:
        """Add new user to the room by creating an event and poking the federation API."""

        hostname = get_domain_from_id(user_id)

        room_version = self.get_success(self.store.get_room_version_id(room_id))

        builder = EventBuilder(
            state=self.state,
            event_auth_handler=self._event_auth_handler,
            store=self.store,
            clock=self.clock,
            hostname=hostname,
            signing_key=self.random_signing_key,
            room_version=KNOWN_ROOM_VERSIONS[room_version],
            room_id=room_id,
            type=EventTypes.Member,
            sender=user_id,
            state_key=user_id,
            content={"membership": Membership.JOIN},
        )

        prev_event_ids = self.get_success(
            self.store.get_latest_event_ids_in_room(room_id)
        )

        event = self.get_success(
            builder.build(prev_event_ids=list(prev_event_ids), auth_event_ids=None)
        )

        self.get_success(self.federation_event_handler.on_receive_pdu(hostname, event))

        # Check that it was successfully persisted.
        self.get_success(self.store.get_event(event.event_id))
        self.get_success(self.store.get_event(event.event_id))