1
0

test_presence.py 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961
  1. # Copyright 2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import itertools
  15. from typing import Optional, cast
  16. from unittest.mock import Mock, call
  17. from parameterized import parameterized
  18. from signedjson.key import generate_signing_key
  19. from twisted.test.proto_helpers import MemoryReactor
  20. from synapse.api.constants import EventTypes, Membership, PresenceState
  21. from synapse.api.presence import UserDevicePresenceState, UserPresenceState
  22. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS
  23. from synapse.events.builder import EventBuilder
  24. from synapse.federation.sender import FederationSender
  25. from synapse.handlers.presence import (
  26. BUSY_ONLINE_TIMEOUT,
  27. EXTERNAL_PROCESS_EXPIRY,
  28. FEDERATION_PING_INTERVAL,
  29. FEDERATION_TIMEOUT,
  30. IDLE_TIMER,
  31. LAST_ACTIVE_GRANULARITY,
  32. SYNC_ONLINE_TIMEOUT,
  33. PresenceHandler,
  34. handle_timeout,
  35. handle_update,
  36. )
  37. from synapse.rest import admin
  38. from synapse.rest.client import room
  39. from synapse.server import HomeServer
  40. from synapse.storage.database import LoggingDatabaseConnection
  41. from synapse.types import JsonDict, UserID, get_domain_from_id
  42. from synapse.util import Clock
  43. from tests import unittest
  44. from tests.replication._base import BaseMultiWorkerStreamTestCase
  45. class PresenceUpdateTestCase(unittest.HomeserverTestCase):
  46. servlets = [admin.register_servlets]
  47. def prepare(
  48. self, reactor: MemoryReactor, clock: Clock, homeserver: HomeServer
  49. ) -> None:
  50. self.store = homeserver.get_datastores().main
  51. def test_offline_to_online(self) -> None:
  52. wheel_timer = Mock()
  53. user_id = "@foo:bar"
  54. now = 5000000
  55. prev_state = UserPresenceState.default(user_id)
  56. new_state = prev_state.copy_and_replace(
  57. state=PresenceState.ONLINE, last_active_ts=now
  58. )
  59. state, persist_and_notify, federation_ping = handle_update(
  60. prev_state,
  61. new_state,
  62. is_mine=True,
  63. wheel_timer=wheel_timer,
  64. now=now,
  65. persist=False,
  66. )
  67. self.assertTrue(persist_and_notify)
  68. self.assertTrue(state.currently_active)
  69. self.assertEqual(new_state.state, state.state)
  70. self.assertEqual(new_state.status_msg, state.status_msg)
  71. self.assertEqual(state.last_federation_update_ts, now)
  72. self.assertEqual(wheel_timer.insert.call_count, 3)
  73. wheel_timer.insert.assert_has_calls(
  74. [
  75. call(now=now, obj=user_id, then=new_state.last_active_ts + IDLE_TIMER),
  76. call(
  77. now=now,
  78. obj=user_id,
  79. then=new_state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT,
  80. ),
  81. call(
  82. now=now,
  83. obj=user_id,
  84. then=new_state.last_active_ts + LAST_ACTIVE_GRANULARITY,
  85. ),
  86. ],
  87. any_order=True,
  88. )
  89. def test_online_to_online(self) -> None:
  90. wheel_timer = Mock()
  91. user_id = "@foo:bar"
  92. now = 5000000
  93. prev_state = UserPresenceState.default(user_id)
  94. prev_state = prev_state.copy_and_replace(
  95. state=PresenceState.ONLINE, last_active_ts=now, currently_active=True
  96. )
  97. new_state = prev_state.copy_and_replace(
  98. state=PresenceState.ONLINE, last_active_ts=now
  99. )
  100. state, persist_and_notify, federation_ping = handle_update(
  101. prev_state,
  102. new_state,
  103. is_mine=True,
  104. wheel_timer=wheel_timer,
  105. now=now,
  106. persist=False,
  107. )
  108. self.assertFalse(persist_and_notify)
  109. self.assertTrue(federation_ping)
  110. self.assertTrue(state.currently_active)
  111. self.assertEqual(new_state.state, state.state)
  112. self.assertEqual(new_state.status_msg, state.status_msg)
  113. self.assertEqual(state.last_federation_update_ts, now)
  114. self.assertEqual(wheel_timer.insert.call_count, 3)
  115. wheel_timer.insert.assert_has_calls(
  116. [
  117. call(now=now, obj=user_id, then=new_state.last_active_ts + IDLE_TIMER),
  118. call(
  119. now=now,
  120. obj=user_id,
  121. then=new_state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT,
  122. ),
  123. call(
  124. now=now,
  125. obj=user_id,
  126. then=new_state.last_active_ts + LAST_ACTIVE_GRANULARITY,
  127. ),
  128. ],
  129. any_order=True,
  130. )
  131. def test_online_to_online_last_active_noop(self) -> None:
  132. wheel_timer = Mock()
  133. user_id = "@foo:bar"
  134. now = 5000000
  135. prev_state = UserPresenceState.default(user_id)
  136. prev_state = prev_state.copy_and_replace(
  137. state=PresenceState.ONLINE,
  138. last_active_ts=now - LAST_ACTIVE_GRANULARITY - 10,
  139. currently_active=True,
  140. )
  141. new_state = prev_state.copy_and_replace(
  142. state=PresenceState.ONLINE, last_active_ts=now
  143. )
  144. state, persist_and_notify, federation_ping = handle_update(
  145. prev_state,
  146. new_state,
  147. is_mine=True,
  148. wheel_timer=wheel_timer,
  149. now=now,
  150. persist=False,
  151. )
  152. self.assertFalse(persist_and_notify)
  153. self.assertTrue(federation_ping)
  154. self.assertTrue(state.currently_active)
  155. self.assertEqual(new_state.state, state.state)
  156. self.assertEqual(new_state.status_msg, state.status_msg)
  157. self.assertEqual(state.last_federation_update_ts, now)
  158. self.assertEqual(wheel_timer.insert.call_count, 3)
  159. wheel_timer.insert.assert_has_calls(
  160. [
  161. call(now=now, obj=user_id, then=new_state.last_active_ts + IDLE_TIMER),
  162. call(
  163. now=now,
  164. obj=user_id,
  165. then=new_state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT,
  166. ),
  167. call(
  168. now=now,
  169. obj=user_id,
  170. then=new_state.last_active_ts + LAST_ACTIVE_GRANULARITY,
  171. ),
  172. ],
  173. any_order=True,
  174. )
  175. def test_online_to_online_last_active(self) -> None:
  176. wheel_timer = Mock()
  177. user_id = "@foo:bar"
  178. now = 5000000
  179. prev_state = UserPresenceState.default(user_id)
  180. prev_state = prev_state.copy_and_replace(
  181. state=PresenceState.ONLINE,
  182. last_active_ts=now - LAST_ACTIVE_GRANULARITY - 1,
  183. currently_active=True,
  184. )
  185. new_state = prev_state.copy_and_replace(state=PresenceState.ONLINE)
  186. state, persist_and_notify, federation_ping = handle_update(
  187. prev_state,
  188. new_state,
  189. is_mine=True,
  190. wheel_timer=wheel_timer,
  191. now=now,
  192. persist=False,
  193. )
  194. self.assertTrue(persist_and_notify)
  195. self.assertFalse(state.currently_active)
  196. self.assertEqual(new_state.state, state.state)
  197. self.assertEqual(new_state.status_msg, state.status_msg)
  198. self.assertEqual(state.last_federation_update_ts, now)
  199. self.assertEqual(wheel_timer.insert.call_count, 2)
  200. wheel_timer.insert.assert_has_calls(
  201. [
  202. call(now=now, obj=user_id, then=new_state.last_active_ts + IDLE_TIMER),
  203. call(
  204. now=now,
  205. obj=user_id,
  206. then=new_state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT,
  207. ),
  208. ],
  209. any_order=True,
  210. )
  211. def test_remote_ping_timer(self) -> None:
  212. wheel_timer = Mock()
  213. user_id = "@foo:bar"
  214. now = 5000000
  215. prev_state = UserPresenceState.default(user_id)
  216. prev_state = prev_state.copy_and_replace(
  217. state=PresenceState.ONLINE, last_active_ts=now
  218. )
  219. new_state = prev_state.copy_and_replace(state=PresenceState.ONLINE)
  220. state, persist_and_notify, federation_ping = handle_update(
  221. prev_state,
  222. new_state,
  223. is_mine=False,
  224. wheel_timer=wheel_timer,
  225. now=now,
  226. persist=False,
  227. )
  228. self.assertFalse(persist_and_notify)
  229. self.assertFalse(federation_ping)
  230. self.assertFalse(state.currently_active)
  231. self.assertEqual(new_state.state, state.state)
  232. self.assertEqual(new_state.status_msg, state.status_msg)
  233. self.assertEqual(wheel_timer.insert.call_count, 1)
  234. wheel_timer.insert.assert_has_calls(
  235. [
  236. call(
  237. now=now,
  238. obj=user_id,
  239. then=new_state.last_federation_update_ts + FEDERATION_TIMEOUT,
  240. )
  241. ],
  242. any_order=True,
  243. )
  244. def test_online_to_offline(self) -> None:
  245. wheel_timer = Mock()
  246. user_id = "@foo:bar"
  247. now = 5000000
  248. prev_state = UserPresenceState.default(user_id)
  249. prev_state = prev_state.copy_and_replace(
  250. state=PresenceState.ONLINE, last_active_ts=now, currently_active=True
  251. )
  252. new_state = prev_state.copy_and_replace(state=PresenceState.OFFLINE)
  253. state, persist_and_notify, federation_ping = handle_update(
  254. prev_state,
  255. new_state,
  256. is_mine=True,
  257. wheel_timer=wheel_timer,
  258. now=now,
  259. persist=False,
  260. )
  261. self.assertTrue(persist_and_notify)
  262. self.assertEqual(new_state.state, state.state)
  263. self.assertEqual(state.last_federation_update_ts, now)
  264. self.assertEqual(wheel_timer.insert.call_count, 0)
  265. def test_online_to_idle(self) -> None:
  266. wheel_timer = Mock()
  267. user_id = "@foo:bar"
  268. now = 5000000
  269. prev_state = UserPresenceState.default(user_id)
  270. prev_state = prev_state.copy_and_replace(
  271. state=PresenceState.ONLINE, last_active_ts=now, currently_active=True
  272. )
  273. new_state = prev_state.copy_and_replace(state=PresenceState.UNAVAILABLE)
  274. state, persist_and_notify, federation_ping = handle_update(
  275. prev_state,
  276. new_state,
  277. is_mine=True,
  278. wheel_timer=wheel_timer,
  279. now=now,
  280. persist=False,
  281. )
  282. self.assertTrue(persist_and_notify)
  283. self.assertEqual(new_state.state, state.state)
  284. self.assertEqual(state.last_federation_update_ts, now)
  285. self.assertEqual(new_state.state, state.state)
  286. self.assertEqual(new_state.status_msg, state.status_msg)
  287. self.assertEqual(wheel_timer.insert.call_count, 1)
  288. wheel_timer.insert.assert_has_calls(
  289. [
  290. call(
  291. now=now,
  292. obj=user_id,
  293. then=new_state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT,
  294. )
  295. ],
  296. any_order=True,
  297. )
  298. def test_persisting_presence_updates(self) -> None:
  299. """Tests that the latest presence state for each user is persisted correctly"""
  300. # Create some test users and presence states for them
  301. presence_states = []
  302. for i in range(5):
  303. user_id = self.register_user(f"user_{i}", "password")
  304. presence_state = UserPresenceState(
  305. user_id=user_id,
  306. state="online",
  307. last_active_ts=1,
  308. last_federation_update_ts=1,
  309. last_user_sync_ts=1,
  310. status_msg="I'm online!",
  311. currently_active=True,
  312. )
  313. presence_states.append(presence_state)
  314. # Persist these presence updates to the database
  315. self.get_success(self.store.update_presence(presence_states))
  316. # Check that each update is present in the database
  317. db_presence_states_raw = self.get_success(
  318. self.store.get_all_presence_updates(
  319. instance_name="master",
  320. last_id=0,
  321. current_id=len(presence_states) + 1,
  322. limit=len(presence_states),
  323. )
  324. )
  325. # Extract presence update user ID and state information into lists of tuples
  326. db_presence_states = [(ps[0], ps[1]) for _, ps in db_presence_states_raw[0]]
  327. presence_states_compare = [(ps.user_id, ps.state) for ps in presence_states]
  328. # Compare what we put into the storage with what we got out.
  329. # They should be identical.
  330. self.assertEqual(presence_states_compare, db_presence_states)
  331. @parameterized.expand(
  332. itertools.permutations(
  333. (
  334. PresenceState.BUSY,
  335. PresenceState.ONLINE,
  336. PresenceState.UNAVAILABLE,
  337. PresenceState.OFFLINE,
  338. ),
  339. 2,
  340. )
  341. )
  342. def test_override(self, initial_state: str, final_state: str) -> None:
  343. """Overridden statuses should not go into the wheel timer."""
  344. wheel_timer = Mock()
  345. user_id = "@foo:bar"
  346. now = 5000000
  347. prev_state = UserPresenceState.default(user_id)
  348. prev_state = prev_state.copy_and_replace(
  349. state=initial_state, last_active_ts=now, currently_active=True
  350. )
  351. new_state = prev_state.copy_and_replace(state=final_state, last_active_ts=now)
  352. handle_update(
  353. prev_state,
  354. new_state,
  355. is_mine=True,
  356. wheel_timer=wheel_timer,
  357. now=now,
  358. persist=True,
  359. )
  360. wheel_timer.insert.assert_not_called()
  361. class PresenceTimeoutTestCase(unittest.TestCase):
  362. """Tests different timers and that the timer does not change `status_msg` of user."""
  363. def test_idle_timer(self) -> None:
  364. user_id = "@foo:bar"
  365. device_id = "dev-1"
  366. status_msg = "I'm here!"
  367. now = 5000000
  368. state = UserPresenceState.default(user_id)
  369. state = state.copy_and_replace(
  370. state=PresenceState.ONLINE,
  371. last_active_ts=now - IDLE_TIMER - 1,
  372. last_user_sync_ts=now,
  373. status_msg=status_msg,
  374. )
  375. device_state = UserDevicePresenceState(
  376. user_id=user_id,
  377. device_id=device_id,
  378. state=state.state,
  379. last_active_ts=state.last_active_ts,
  380. last_sync_ts=state.last_user_sync_ts,
  381. )
  382. new_state = handle_timeout(
  383. state,
  384. is_mine=True,
  385. syncing_device_ids=set(),
  386. user_devices={device_id: device_state},
  387. now=now,
  388. )
  389. self.assertIsNotNone(new_state)
  390. assert new_state is not None
  391. self.assertEqual(new_state.state, PresenceState.UNAVAILABLE)
  392. self.assertEqual(new_state.status_msg, status_msg)
  393. def test_busy_no_idle(self) -> None:
  394. """
  395. Tests that a user setting their presence to busy but idling doesn't turn their
  396. presence state into unavailable.
  397. """
  398. user_id = "@foo:bar"
  399. device_id = "dev-1"
  400. status_msg = "I'm here!"
  401. now = 5000000
  402. state = UserPresenceState.default(user_id)
  403. state = state.copy_and_replace(
  404. state=PresenceState.BUSY,
  405. last_active_ts=now - IDLE_TIMER - 1,
  406. last_user_sync_ts=now,
  407. status_msg=status_msg,
  408. )
  409. device_state = UserDevicePresenceState(
  410. user_id=user_id,
  411. device_id=device_id,
  412. state=state.state,
  413. last_active_ts=state.last_active_ts,
  414. last_sync_ts=state.last_user_sync_ts,
  415. )
  416. new_state = handle_timeout(
  417. state,
  418. is_mine=True,
  419. syncing_device_ids=set(),
  420. user_devices={device_id: device_state},
  421. now=now,
  422. )
  423. self.assertIsNotNone(new_state)
  424. assert new_state is not None
  425. self.assertEqual(new_state.state, PresenceState.BUSY)
  426. self.assertEqual(new_state.status_msg, status_msg)
  427. def test_sync_timeout(self) -> None:
  428. user_id = "@foo:bar"
  429. device_id = "dev-1"
  430. status_msg = "I'm here!"
  431. now = 5000000
  432. state = UserPresenceState.default(user_id)
  433. state = state.copy_and_replace(
  434. state=PresenceState.ONLINE,
  435. last_active_ts=0,
  436. last_user_sync_ts=now - SYNC_ONLINE_TIMEOUT - 1,
  437. status_msg=status_msg,
  438. )
  439. device_state = UserDevicePresenceState(
  440. user_id=user_id,
  441. device_id=device_id,
  442. state=state.state,
  443. last_active_ts=state.last_active_ts,
  444. last_sync_ts=state.last_user_sync_ts,
  445. )
  446. new_state = handle_timeout(
  447. state,
  448. is_mine=True,
  449. syncing_device_ids=set(),
  450. user_devices={device_id: device_state},
  451. now=now,
  452. )
  453. self.assertIsNotNone(new_state)
  454. assert new_state is not None
  455. self.assertEqual(new_state.state, PresenceState.OFFLINE)
  456. self.assertEqual(new_state.status_msg, status_msg)
  457. def test_sync_online(self) -> None:
  458. user_id = "@foo:bar"
  459. device_id = "dev-1"
  460. status_msg = "I'm here!"
  461. now = 5000000
  462. state = UserPresenceState.default(user_id)
  463. state = state.copy_and_replace(
  464. state=PresenceState.ONLINE,
  465. last_active_ts=now - SYNC_ONLINE_TIMEOUT - 1,
  466. last_user_sync_ts=now - SYNC_ONLINE_TIMEOUT - 1,
  467. status_msg=status_msg,
  468. )
  469. device_state = UserDevicePresenceState(
  470. user_id=user_id,
  471. device_id=device_id,
  472. state=state.state,
  473. last_active_ts=state.last_active_ts,
  474. last_sync_ts=state.last_user_sync_ts,
  475. )
  476. new_state = handle_timeout(
  477. state,
  478. is_mine=True,
  479. syncing_device_ids={(user_id, device_id)},
  480. user_devices={device_id: device_state},
  481. now=now,
  482. )
  483. self.assertIsNotNone(new_state)
  484. assert new_state is not None
  485. self.assertEqual(new_state.state, PresenceState.ONLINE)
  486. self.assertEqual(new_state.status_msg, status_msg)
  487. def test_federation_ping(self) -> None:
  488. user_id = "@foo:bar"
  489. device_id = "dev-1"
  490. status_msg = "I'm here!"
  491. now = 5000000
  492. state = UserPresenceState.default(user_id)
  493. state = state.copy_and_replace(
  494. state=PresenceState.ONLINE,
  495. last_active_ts=now,
  496. last_user_sync_ts=now,
  497. last_federation_update_ts=now - FEDERATION_PING_INTERVAL - 1,
  498. status_msg=status_msg,
  499. )
  500. device_state = UserDevicePresenceState(
  501. user_id=user_id,
  502. device_id=device_id,
  503. state=state.state,
  504. last_active_ts=state.last_active_ts,
  505. last_sync_ts=state.last_user_sync_ts,
  506. )
  507. new_state = handle_timeout(
  508. state,
  509. is_mine=True,
  510. syncing_device_ids=set(),
  511. user_devices={device_id: device_state},
  512. now=now,
  513. )
  514. self.assertIsNotNone(new_state)
  515. self.assertEqual(state, new_state)
  516. def test_no_timeout(self) -> None:
  517. user_id = "@foo:bar"
  518. device_id = "dev-1"
  519. now = 5000000
  520. state = UserPresenceState.default(user_id)
  521. state = state.copy_and_replace(
  522. state=PresenceState.ONLINE,
  523. last_active_ts=now,
  524. last_user_sync_ts=now,
  525. last_federation_update_ts=now,
  526. )
  527. device_state = UserDevicePresenceState(
  528. user_id=user_id,
  529. device_id=device_id,
  530. state=state.state,
  531. last_active_ts=state.last_active_ts,
  532. last_sync_ts=state.last_user_sync_ts,
  533. )
  534. new_state = handle_timeout(
  535. state,
  536. is_mine=True,
  537. syncing_device_ids=set(),
  538. user_devices={device_id: device_state},
  539. now=now,
  540. )
  541. self.assertIsNone(new_state)
  542. def test_federation_timeout(self) -> None:
  543. user_id = "@foo:bar"
  544. status_msg = "I'm here!"
  545. now = 5000000
  546. state = UserPresenceState.default(user_id)
  547. state = state.copy_and_replace(
  548. state=PresenceState.ONLINE,
  549. last_active_ts=now,
  550. last_user_sync_ts=now,
  551. last_federation_update_ts=now - FEDERATION_TIMEOUT - 1,
  552. status_msg=status_msg,
  553. )
  554. # Note that this is a remote user so we do not have their device information.
  555. new_state = handle_timeout(
  556. state, is_mine=False, syncing_device_ids=set(), user_devices={}, now=now
  557. )
  558. self.assertIsNotNone(new_state)
  559. assert new_state is not None
  560. self.assertEqual(new_state.state, PresenceState.OFFLINE)
  561. self.assertEqual(new_state.status_msg, status_msg)
  562. def test_last_active(self) -> None:
  563. user_id = "@foo:bar"
  564. device_id = "dev-1"
  565. status_msg = "I'm here!"
  566. now = 5000000
  567. state = UserPresenceState.default(user_id)
  568. state = state.copy_and_replace(
  569. state=PresenceState.ONLINE,
  570. last_active_ts=now - LAST_ACTIVE_GRANULARITY - 1,
  571. last_user_sync_ts=now,
  572. last_federation_update_ts=now,
  573. status_msg=status_msg,
  574. )
  575. device_state = UserDevicePresenceState(
  576. user_id=user_id,
  577. device_id=device_id,
  578. state=state.state,
  579. last_active_ts=state.last_active_ts,
  580. last_sync_ts=state.last_user_sync_ts,
  581. )
  582. new_state = handle_timeout(
  583. state,
  584. is_mine=True,
  585. syncing_device_ids=set(),
  586. user_devices={device_id: device_state},
  587. now=now,
  588. )
  589. self.assertIsNotNone(new_state)
  590. self.assertEqual(state, new_state)
  591. class PresenceHandlerInitTestCase(unittest.HomeserverTestCase):
  592. def default_config(self) -> JsonDict:
  593. config = super().default_config()
  594. # Disable background tasks on this worker so that the PresenceHandler isn't
  595. # loaded until we request it.
  596. config["run_background_tasks_on"] = "other"
  597. return config
  598. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  599. self.user_id = f"@test:{self.hs.config.server.server_name}"
  600. self.device_id = "dev-1"
  601. # Move the reactor to the initial time.
  602. self.reactor.advance(1000)
  603. now = self.clock.time_msec()
  604. main_store = hs.get_datastores().main
  605. self.get_success(
  606. main_store.update_presence(
  607. [
  608. UserPresenceState(
  609. user_id=self.user_id,
  610. state=PresenceState.ONLINE,
  611. last_active_ts=now,
  612. last_federation_update_ts=now,
  613. last_user_sync_ts=now,
  614. status_msg=None,
  615. currently_active=True,
  616. )
  617. ]
  618. )
  619. )
  620. # Regenerate the preloaded presence information on PresenceStore.
  621. def refill_presence(db_conn: LoggingDatabaseConnection) -> None:
  622. main_store._presence_on_startup = main_store._get_active_presence(db_conn)
  623. self.get_success(main_store.db_pool.runWithConnection(refill_presence))
  624. def test_restored_presence_idles(self) -> None:
  625. """The presence state restored from the database should not persist forever."""
  626. # Get the handler (which kicks off a bunch of timers).
  627. presence_handler = self.hs.get_presence_handler()
  628. # Assert the user is online.
  629. state = self.get_success(
  630. presence_handler.get_state(UserID.from_string(self.user_id))
  631. )
  632. self.assertEqual(state.state, PresenceState.ONLINE)
  633. # Advance such that the user should timeout.
  634. self.reactor.advance(SYNC_ONLINE_TIMEOUT / 1000)
  635. self.reactor.pump([5])
  636. # Check that the user is now offline.
  637. state = self.get_success(
  638. presence_handler.get_state(UserID.from_string(self.user_id))
  639. )
  640. self.assertEqual(state.state, PresenceState.OFFLINE)
  641. @parameterized.expand(
  642. [
  643. (PresenceState.BUSY, PresenceState.BUSY),
  644. (PresenceState.ONLINE, PresenceState.ONLINE),
  645. (PresenceState.UNAVAILABLE, PresenceState.ONLINE),
  646. # Offline syncs don't update the state.
  647. (PresenceState.OFFLINE, PresenceState.ONLINE),
  648. ]
  649. )
  650. @unittest.override_config({"experimental_features": {"msc3026_enabled": True}})
  651. def test_restored_presence_online_after_sync(
  652. self, sync_state: str, expected_state: str
  653. ) -> None:
  654. """
  655. The presence state restored from the database should be overridden with sync after a timeout.
  656. Args:
  657. sync_state: The presence state of the new sync.
  658. expected_state: The expected presence right after the sync.
  659. """
  660. # Get the handler (which kicks off a bunch of timers).
  661. presence_handler = self.hs.get_presence_handler()
  662. # Assert the user is online, as restored.
  663. state = self.get_success(
  664. presence_handler.get_state(UserID.from_string(self.user_id))
  665. )
  666. self.assertEqual(state.state, PresenceState.ONLINE)
  667. # Advance slightly and sync.
  668. self.reactor.advance(SYNC_ONLINE_TIMEOUT / 1000 / 2)
  669. self.get_success(
  670. presence_handler.user_syncing(
  671. self.user_id,
  672. self.device_id,
  673. sync_state != PresenceState.OFFLINE,
  674. sync_state,
  675. )
  676. )
  677. # Assert the user is in the expected state.
  678. state = self.get_success(
  679. presence_handler.get_state(UserID.from_string(self.user_id))
  680. )
  681. self.assertEqual(state.state, expected_state)
  682. # Advance such that the user's preloaded data times out, but not the new sync.
  683. self.reactor.advance(SYNC_ONLINE_TIMEOUT / 1000 / 2)
  684. self.reactor.pump([5])
  685. # Check that the user is in the sync state (as the client is currently syncing still).
  686. state = self.get_success(
  687. presence_handler.get_state(UserID.from_string(self.user_id))
  688. )
  689. self.assertEqual(state.state, sync_state)
  690. class PresenceHandlerTestCase(BaseMultiWorkerStreamTestCase):
  691. user_id = "@test:server"
  692. user_id_obj = UserID.from_string(user_id)
  693. device_id = "dev-1"
  694. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  695. self.presence_handler = hs.get_presence_handler()
  696. def test_external_process_timeout(self) -> None:
  697. """Test that if an external process doesn't update the records for a while
  698. we time out their syncing users presence.
  699. """
  700. # Create a worker and use it to handle /sync traffic instead.
  701. # This is used to test that presence changes get replicated from workers
  702. # to the main process correctly.
  703. worker_to_sync_against = self.make_worker_hs(
  704. "synapse.app.generic_worker", {"worker_name": "synchrotron"}
  705. )
  706. worker_presence_handler = worker_to_sync_against.get_presence_handler()
  707. self.get_success(
  708. worker_presence_handler.user_syncing(
  709. self.user_id, self.device_id, True, PresenceState.ONLINE
  710. ),
  711. by=0.1,
  712. )
  713. # Check that if we wait a while without telling the handler the user has
  714. # stopped syncing that their presence state doesn't get timed out.
  715. self.reactor.advance(EXTERNAL_PROCESS_EXPIRY / 2)
  716. state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
  717. self.assertEqual(state.state, PresenceState.ONLINE)
  718. # Check that if the external process timeout fires, then the syncing
  719. # user gets timed out
  720. self.reactor.advance(EXTERNAL_PROCESS_EXPIRY)
  721. state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
  722. self.assertEqual(state.state, PresenceState.OFFLINE)
  723. def test_user_goes_offline_by_timeout_status_msg_remain(self) -> None:
  724. """Test that if a user doesn't update the records for a while
  725. users presence goes `OFFLINE` because of timeout and `status_msg` remains.
  726. """
  727. status_msg = "I'm here!"
  728. # Mark user as online
  729. self._set_presencestate_with_status_msg(PresenceState.ONLINE, status_msg)
  730. # Check that if we wait a while without telling the handler the user has
  731. # stopped syncing that their presence state doesn't get timed out.
  732. self.reactor.advance(SYNC_ONLINE_TIMEOUT / 2)
  733. state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
  734. self.assertEqual(state.state, PresenceState.ONLINE)
  735. self.assertEqual(state.status_msg, status_msg)
  736. # Check that if the timeout fires, then the syncing user gets timed out
  737. self.reactor.advance(SYNC_ONLINE_TIMEOUT)
  738. state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
  739. # status_msg should remain even after going offline
  740. self.assertEqual(state.state, PresenceState.OFFLINE)
  741. self.assertEqual(state.status_msg, status_msg)
  742. def test_user_goes_offline_manually_with_no_status_msg(self) -> None:
  743. """Test that if a user change presence manually to `OFFLINE`
  744. and no status is set, that `status_msg` is `None`.
  745. """
  746. status_msg = "I'm here!"
  747. # Mark user as online
  748. self._set_presencestate_with_status_msg(PresenceState.ONLINE, status_msg)
  749. # Mark user as offline
  750. self.get_success(
  751. self.presence_handler.set_state(
  752. self.user_id_obj, self.device_id, {"presence": PresenceState.OFFLINE}
  753. )
  754. )
  755. state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
  756. self.assertEqual(state.state, PresenceState.OFFLINE)
  757. self.assertEqual(state.status_msg, None)
  758. def test_user_goes_offline_manually_with_status_msg(self) -> None:
  759. """Test that if a user change presence manually to `OFFLINE`
  760. and a status is set, that `status_msg` appears.
  761. """
  762. status_msg = "I'm here!"
  763. # Mark user as online
  764. self._set_presencestate_with_status_msg(PresenceState.ONLINE, status_msg)
  765. # Mark user as offline
  766. self._set_presencestate_with_status_msg(PresenceState.OFFLINE, "And now here.")
  767. def test_user_reset_online_with_no_status(self) -> None:
  768. """Test that if a user set again the presence manually
  769. and no status is set, that `status_msg` is `None`.
  770. """
  771. status_msg = "I'm here!"
  772. # Mark user as online
  773. self._set_presencestate_with_status_msg(PresenceState.ONLINE, status_msg)
  774. # Mark user as online again
  775. self.get_success(
  776. self.presence_handler.set_state(
  777. self.user_id_obj, self.device_id, {"presence": PresenceState.ONLINE}
  778. )
  779. )
  780. state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
  781. # status_msg should remain even after going offline
  782. self.assertEqual(state.state, PresenceState.ONLINE)
  783. self.assertEqual(state.status_msg, None)
  784. def test_set_presence_with_status_msg_none(self) -> None:
  785. """Test that if a user set again the presence manually
  786. and status is `None`, that `status_msg` is `None`.
  787. """
  788. status_msg = "I'm here!"
  789. # Mark user as online
  790. self._set_presencestate_with_status_msg(PresenceState.ONLINE, status_msg)
  791. # Mark user as online and `status_msg = None`
  792. self._set_presencestate_with_status_msg(PresenceState.ONLINE, None)
  793. def test_set_presence_from_syncing_not_set(self) -> None:
  794. """Test that presence is not set by syncing if affect_presence is false"""
  795. status_msg = "I'm here!"
  796. self._set_presencestate_with_status_msg(PresenceState.UNAVAILABLE, status_msg)
  797. self.get_success(
  798. self.presence_handler.user_syncing(
  799. self.user_id, self.device_id, False, PresenceState.ONLINE
  800. )
  801. )
  802. state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
  803. # we should still be unavailable
  804. self.assertEqual(state.state, PresenceState.UNAVAILABLE)
  805. # and status message should still be the same
  806. self.assertEqual(state.status_msg, status_msg)
  807. def test_set_presence_from_syncing_is_set(self) -> None:
  808. """Test that presence is set by syncing if affect_presence is true"""
  809. status_msg = "I'm here!"
  810. self._set_presencestate_with_status_msg(PresenceState.UNAVAILABLE, status_msg)
  811. self.get_success(
  812. self.presence_handler.user_syncing(
  813. self.user_id, self.device_id, True, PresenceState.ONLINE
  814. )
  815. )
  816. state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
  817. # we should now be online
  818. self.assertEqual(state.state, PresenceState.ONLINE)
  819. @parameterized.expand(
  820. # A list of tuples of 4 strings:
  821. #
  822. # * The presence state of device 1.
  823. # * The presence state of device 2.
  824. # * The expected user presence state after both devices have synced.
  825. # * The expected user presence state after device 1 has idled.
  826. # * The expected user presence state after device 2 has idled.
  827. # * True to use workers, False a monolith.
  828. [
  829. (*cases, workers)
  830. for workers in (False, True)
  831. for cases in [
  832. # If both devices have the same state, online should eventually idle.
  833. # Otherwise, the state doesn't change.
  834. (
  835. PresenceState.BUSY,
  836. PresenceState.BUSY,
  837. PresenceState.BUSY,
  838. PresenceState.BUSY,
  839. PresenceState.BUSY,
  840. ),
  841. (
  842. PresenceState.ONLINE,
  843. PresenceState.ONLINE,
  844. PresenceState.ONLINE,
  845. PresenceState.ONLINE,
  846. PresenceState.UNAVAILABLE,
  847. ),
  848. (
  849. PresenceState.UNAVAILABLE,
  850. PresenceState.UNAVAILABLE,
  851. PresenceState.UNAVAILABLE,
  852. PresenceState.UNAVAILABLE,
  853. PresenceState.UNAVAILABLE,
  854. ),
  855. (
  856. PresenceState.OFFLINE,
  857. PresenceState.OFFLINE,
  858. PresenceState.OFFLINE,
  859. PresenceState.OFFLINE,
  860. PresenceState.OFFLINE,
  861. ),
  862. # If the second device has a "lower" state it should fallback to it,
  863. # except for "busy" which overrides.
  864. (
  865. PresenceState.BUSY,
  866. PresenceState.ONLINE,
  867. PresenceState.BUSY,
  868. PresenceState.BUSY,
  869. PresenceState.BUSY,
  870. ),
  871. (
  872. PresenceState.BUSY,
  873. PresenceState.UNAVAILABLE,
  874. PresenceState.BUSY,
  875. PresenceState.BUSY,
  876. PresenceState.BUSY,
  877. ),
  878. (
  879. PresenceState.BUSY,
  880. PresenceState.OFFLINE,
  881. PresenceState.BUSY,
  882. PresenceState.BUSY,
  883. PresenceState.BUSY,
  884. ),
  885. (
  886. PresenceState.ONLINE,
  887. PresenceState.UNAVAILABLE,
  888. PresenceState.ONLINE,
  889. PresenceState.UNAVAILABLE,
  890. PresenceState.UNAVAILABLE,
  891. ),
  892. (
  893. PresenceState.ONLINE,
  894. PresenceState.OFFLINE,
  895. PresenceState.ONLINE,
  896. PresenceState.UNAVAILABLE,
  897. PresenceState.UNAVAILABLE,
  898. ),
  899. (
  900. PresenceState.UNAVAILABLE,
  901. PresenceState.OFFLINE,
  902. PresenceState.UNAVAILABLE,
  903. PresenceState.UNAVAILABLE,
  904. PresenceState.UNAVAILABLE,
  905. ),
  906. # If the second device has a "higher" state it should override.
  907. (
  908. PresenceState.ONLINE,
  909. PresenceState.BUSY,
  910. PresenceState.BUSY,
  911. PresenceState.BUSY,
  912. PresenceState.BUSY,
  913. ),
  914. (
  915. PresenceState.UNAVAILABLE,
  916. PresenceState.BUSY,
  917. PresenceState.BUSY,
  918. PresenceState.BUSY,
  919. PresenceState.BUSY,
  920. ),
  921. (
  922. PresenceState.OFFLINE,
  923. PresenceState.BUSY,
  924. PresenceState.BUSY,
  925. PresenceState.BUSY,
  926. PresenceState.BUSY,
  927. ),
  928. (
  929. PresenceState.UNAVAILABLE,
  930. PresenceState.ONLINE,
  931. PresenceState.ONLINE,
  932. PresenceState.ONLINE,
  933. PresenceState.UNAVAILABLE,
  934. ),
  935. (
  936. PresenceState.OFFLINE,
  937. PresenceState.ONLINE,
  938. PresenceState.ONLINE,
  939. PresenceState.ONLINE,
  940. PresenceState.UNAVAILABLE,
  941. ),
  942. (
  943. PresenceState.OFFLINE,
  944. PresenceState.UNAVAILABLE,
  945. PresenceState.UNAVAILABLE,
  946. PresenceState.UNAVAILABLE,
  947. PresenceState.UNAVAILABLE,
  948. ),
  949. ]
  950. ],
  951. name_func=lambda testcase_func, param_num, params: f"{testcase_func.__name__}_{param_num}_{'workers' if params.args[5] else 'monolith'}",
  952. )
  953. @unittest.override_config({"experimental_features": {"msc3026_enabled": True}})
  954. def test_set_presence_from_syncing_multi_device(
  955. self,
  956. dev_1_state: str,
  957. dev_2_state: str,
  958. expected_state_1: str,
  959. expected_state_2: str,
  960. expected_state_3: str,
  961. test_with_workers: bool,
  962. ) -> None:
  963. """
  964. Test the behaviour of multiple devices syncing at the same time.
  965. Roughly the user's presence state should be set to the "highest" priority
  966. of all the devices. When a device then goes offline its state should be
  967. discarded and the next highest should win.
  968. Note that these tests use the idle timer (and don't close the syncs), it
  969. is unlikely that a *single* sync would last this long, but is close enough
  970. to continually syncing with that current state.
  971. """
  972. user_id = f"@test:{self.hs.config.server.server_name}"
  973. # By default, we call /sync against the main process.
  974. worker_presence_handler = self.presence_handler
  975. if test_with_workers:
  976. # Create a worker and use it to handle /sync traffic instead.
  977. # This is used to test that presence changes get replicated from workers
  978. # to the main process correctly.
  979. worker_to_sync_against = self.make_worker_hs(
  980. "synapse.app.generic_worker", {"worker_name": "synchrotron"}
  981. )
  982. worker_presence_handler = worker_to_sync_against.get_presence_handler()
  983. # 1. Sync with the first device.
  984. self.get_success(
  985. worker_presence_handler.user_syncing(
  986. user_id,
  987. "dev-1",
  988. affect_presence=dev_1_state != PresenceState.OFFLINE,
  989. presence_state=dev_1_state,
  990. ),
  991. by=0.01,
  992. )
  993. # 2. Wait half the idle timer.
  994. self.reactor.advance(IDLE_TIMER / 1000 / 2)
  995. self.reactor.pump([0.1])
  996. # 3. Sync with the second device.
  997. self.get_success(
  998. worker_presence_handler.user_syncing(
  999. user_id,
  1000. "dev-2",
  1001. affect_presence=dev_2_state != PresenceState.OFFLINE,
  1002. presence_state=dev_2_state,
  1003. ),
  1004. by=0.01,
  1005. )
  1006. # 4. Assert the expected presence state.
  1007. state = self.get_success(
  1008. self.presence_handler.get_state(UserID.from_string(user_id))
  1009. )
  1010. self.assertEqual(state.state, expected_state_1)
  1011. if test_with_workers:
  1012. state = self.get_success(
  1013. worker_presence_handler.get_state(UserID.from_string(user_id))
  1014. )
  1015. self.assertEqual(state.state, expected_state_1)
  1016. # When testing with workers, make another random sync (with any *different*
  1017. # user) to keep the process information from expiring.
  1018. #
  1019. # This is due to EXTERNAL_PROCESS_EXPIRY being equivalent to IDLE_TIMER.
  1020. if test_with_workers:
  1021. with self.get_success(
  1022. worker_presence_handler.user_syncing(
  1023. f"@other-user:{self.hs.config.server.server_name}",
  1024. "dev-3",
  1025. affect_presence=True,
  1026. presence_state=PresenceState.ONLINE,
  1027. ),
  1028. by=0.01,
  1029. ):
  1030. pass
  1031. # 5. Advance such that the first device should be discarded (the idle timer),
  1032. # then pump so _handle_timeouts function to called.
  1033. self.reactor.advance(IDLE_TIMER / 1000 / 2)
  1034. self.reactor.pump([0.01])
  1035. # 6. Assert the expected presence state.
  1036. state = self.get_success(
  1037. self.presence_handler.get_state(UserID.from_string(user_id))
  1038. )
  1039. self.assertEqual(state.state, expected_state_2)
  1040. if test_with_workers:
  1041. state = self.get_success(
  1042. worker_presence_handler.get_state(UserID.from_string(user_id))
  1043. )
  1044. self.assertEqual(state.state, expected_state_2)
  1045. # 7. Advance such that the second device should be discarded (half the idle timer),
  1046. # then pump so _handle_timeouts function to called.
  1047. self.reactor.advance(IDLE_TIMER / 1000 / 2)
  1048. self.reactor.pump([0.1])
  1049. # 8. The devices are still "syncing" (the sync context managers were never
  1050. # closed), so might idle.
  1051. state = self.get_success(
  1052. self.presence_handler.get_state(UserID.from_string(user_id))
  1053. )
  1054. self.assertEqual(state.state, expected_state_3)
  1055. if test_with_workers:
  1056. state = self.get_success(
  1057. worker_presence_handler.get_state(UserID.from_string(user_id))
  1058. )
  1059. self.assertEqual(state.state, expected_state_3)
  1060. @parameterized.expand(
  1061. # A list of tuples of 4 strings:
  1062. #
  1063. # * The presence state of device 1.
  1064. # * The presence state of device 2.
  1065. # * The expected user presence state after both devices have synced.
  1066. # * The expected user presence state after device 1 has stopped syncing.
  1067. # * True to use workers, False a monolith.
  1068. [
  1069. (*cases, workers)
  1070. for workers in (False, True)
  1071. for cases in [
  1072. # If both devices have the same state, nothing exciting should happen.
  1073. (
  1074. PresenceState.BUSY,
  1075. PresenceState.BUSY,
  1076. PresenceState.BUSY,
  1077. PresenceState.BUSY,
  1078. ),
  1079. (
  1080. PresenceState.ONLINE,
  1081. PresenceState.ONLINE,
  1082. PresenceState.ONLINE,
  1083. PresenceState.ONLINE,
  1084. ),
  1085. (
  1086. PresenceState.UNAVAILABLE,
  1087. PresenceState.UNAVAILABLE,
  1088. PresenceState.UNAVAILABLE,
  1089. PresenceState.UNAVAILABLE,
  1090. ),
  1091. (
  1092. PresenceState.OFFLINE,
  1093. PresenceState.OFFLINE,
  1094. PresenceState.OFFLINE,
  1095. PresenceState.OFFLINE,
  1096. ),
  1097. # If the second device has a "lower" state it should fallback to it,
  1098. # except for "busy" which overrides.
  1099. (
  1100. PresenceState.BUSY,
  1101. PresenceState.ONLINE,
  1102. PresenceState.BUSY,
  1103. PresenceState.BUSY,
  1104. ),
  1105. (
  1106. PresenceState.BUSY,
  1107. PresenceState.UNAVAILABLE,
  1108. PresenceState.BUSY,
  1109. PresenceState.BUSY,
  1110. ),
  1111. (
  1112. PresenceState.BUSY,
  1113. PresenceState.OFFLINE,
  1114. PresenceState.BUSY,
  1115. PresenceState.BUSY,
  1116. ),
  1117. (
  1118. PresenceState.ONLINE,
  1119. PresenceState.UNAVAILABLE,
  1120. PresenceState.ONLINE,
  1121. PresenceState.UNAVAILABLE,
  1122. ),
  1123. (
  1124. PresenceState.ONLINE,
  1125. PresenceState.OFFLINE,
  1126. PresenceState.ONLINE,
  1127. PresenceState.OFFLINE,
  1128. ),
  1129. (
  1130. PresenceState.UNAVAILABLE,
  1131. PresenceState.OFFLINE,
  1132. PresenceState.UNAVAILABLE,
  1133. PresenceState.OFFLINE,
  1134. ),
  1135. # If the second device has a "higher" state it should override.
  1136. (
  1137. PresenceState.ONLINE,
  1138. PresenceState.BUSY,
  1139. PresenceState.BUSY,
  1140. PresenceState.BUSY,
  1141. ),
  1142. (
  1143. PresenceState.UNAVAILABLE,
  1144. PresenceState.BUSY,
  1145. PresenceState.BUSY,
  1146. PresenceState.BUSY,
  1147. ),
  1148. (
  1149. PresenceState.OFFLINE,
  1150. PresenceState.BUSY,
  1151. PresenceState.BUSY,
  1152. PresenceState.BUSY,
  1153. ),
  1154. (
  1155. PresenceState.UNAVAILABLE,
  1156. PresenceState.ONLINE,
  1157. PresenceState.ONLINE,
  1158. PresenceState.ONLINE,
  1159. ),
  1160. (
  1161. PresenceState.OFFLINE,
  1162. PresenceState.ONLINE,
  1163. PresenceState.ONLINE,
  1164. PresenceState.ONLINE,
  1165. ),
  1166. (
  1167. PresenceState.OFFLINE,
  1168. PresenceState.UNAVAILABLE,
  1169. PresenceState.UNAVAILABLE,
  1170. PresenceState.UNAVAILABLE,
  1171. ),
  1172. ]
  1173. ],
  1174. name_func=lambda testcase_func, param_num, params: f"{testcase_func.__name__}_{param_num}_{'workers' if params.args[4] else 'monolith'}",
  1175. )
  1176. @unittest.override_config({"experimental_features": {"msc3026_enabled": True}})
  1177. def test_set_presence_from_non_syncing_multi_device(
  1178. self,
  1179. dev_1_state: str,
  1180. dev_2_state: str,
  1181. expected_state_1: str,
  1182. expected_state_2: str,
  1183. test_with_workers: bool,
  1184. ) -> None:
  1185. """
  1186. Test the behaviour of multiple devices syncing at the same time.
  1187. Roughly the user's presence state should be set to the "highest" priority
  1188. of all the devices. When a device then goes offline its state should be
  1189. discarded and the next highest should win.
  1190. Note that these tests use the idle timer (and don't close the syncs), it
  1191. is unlikely that a *single* sync would last this long, but is close enough
  1192. to continually syncing with that current state.
  1193. """
  1194. user_id = f"@test:{self.hs.config.server.server_name}"
  1195. # By default, we call /sync against the main process.
  1196. worker_presence_handler = self.presence_handler
  1197. if test_with_workers:
  1198. # Create a worker and use it to handle /sync traffic instead.
  1199. # This is used to test that presence changes get replicated from workers
  1200. # to the main process correctly.
  1201. worker_to_sync_against = self.make_worker_hs(
  1202. "synapse.app.generic_worker", {"worker_name": "synchrotron"}
  1203. )
  1204. worker_presence_handler = worker_to_sync_against.get_presence_handler()
  1205. # 1. Sync with the first device.
  1206. sync_1 = self.get_success(
  1207. worker_presence_handler.user_syncing(
  1208. user_id,
  1209. "dev-1",
  1210. affect_presence=dev_1_state != PresenceState.OFFLINE,
  1211. presence_state=dev_1_state,
  1212. ),
  1213. by=0.1,
  1214. )
  1215. # 2. Sync with the second device.
  1216. sync_2 = self.get_success(
  1217. worker_presence_handler.user_syncing(
  1218. user_id,
  1219. "dev-2",
  1220. affect_presence=dev_2_state != PresenceState.OFFLINE,
  1221. presence_state=dev_2_state,
  1222. ),
  1223. by=0.1,
  1224. )
  1225. # 3. Assert the expected presence state.
  1226. state = self.get_success(
  1227. self.presence_handler.get_state(UserID.from_string(user_id))
  1228. )
  1229. self.assertEqual(state.state, expected_state_1)
  1230. if test_with_workers:
  1231. state = self.get_success(
  1232. worker_presence_handler.get_state(UserID.from_string(user_id))
  1233. )
  1234. self.assertEqual(state.state, expected_state_1)
  1235. # 4. Disconnect the first device.
  1236. with sync_1:
  1237. pass
  1238. # 5. Advance such that the first device should be discarded (the sync timeout),
  1239. # then pump so _handle_timeouts function to called.
  1240. self.reactor.advance(SYNC_ONLINE_TIMEOUT / 1000)
  1241. self.reactor.pump([5])
  1242. # 6. Assert the expected presence state.
  1243. state = self.get_success(
  1244. self.presence_handler.get_state(UserID.from_string(user_id))
  1245. )
  1246. self.assertEqual(state.state, expected_state_2)
  1247. if test_with_workers:
  1248. state = self.get_success(
  1249. worker_presence_handler.get_state(UserID.from_string(user_id))
  1250. )
  1251. self.assertEqual(state.state, expected_state_2)
  1252. # 7. Disconnect the second device.
  1253. with sync_2:
  1254. pass
  1255. # 8. Advance such that the second device should be discarded (the sync timeout),
  1256. # then pump so _handle_timeouts function to called.
  1257. if dev_1_state == PresenceState.BUSY or dev_2_state == PresenceState.BUSY:
  1258. timeout = BUSY_ONLINE_TIMEOUT
  1259. else:
  1260. timeout = SYNC_ONLINE_TIMEOUT
  1261. self.reactor.advance(timeout / 1000)
  1262. self.reactor.pump([5])
  1263. # 9. There are no more devices, should be offline.
  1264. state = self.get_success(
  1265. self.presence_handler.get_state(UserID.from_string(user_id))
  1266. )
  1267. self.assertEqual(state.state, PresenceState.OFFLINE)
  1268. if test_with_workers:
  1269. state = self.get_success(
  1270. worker_presence_handler.get_state(UserID.from_string(user_id))
  1271. )
  1272. self.assertEqual(state.state, PresenceState.OFFLINE)
  1273. def test_set_presence_from_syncing_keeps_status(self) -> None:
  1274. """Test that presence set by syncing retains status message"""
  1275. status_msg = "I'm here!"
  1276. self._set_presencestate_with_status_msg(PresenceState.UNAVAILABLE, status_msg)
  1277. self.get_success(
  1278. self.presence_handler.user_syncing(
  1279. self.user_id, self.device_id, True, PresenceState.ONLINE
  1280. )
  1281. )
  1282. state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
  1283. # our status message should be the same as it was before
  1284. self.assertEqual(state.status_msg, status_msg)
  1285. @parameterized.expand([(False,), (True,)])
  1286. @unittest.override_config({"experimental_features": {"msc3026_enabled": True}})
  1287. def test_set_presence_from_syncing_keeps_busy(
  1288. self, test_with_workers: bool
  1289. ) -> None:
  1290. """Test that presence set by syncing doesn't affect busy status
  1291. Args:
  1292. test_with_workers: If True, check the presence state of the user by calling
  1293. /sync against a worker, rather than the main process.
  1294. """
  1295. status_msg = "I'm busy!"
  1296. # By default, we call /sync against the main process.
  1297. worker_to_sync_against = self.hs
  1298. if test_with_workers:
  1299. # Create a worker and use it to handle /sync traffic instead.
  1300. # This is used to test that presence changes get replicated from workers
  1301. # to the main process correctly.
  1302. worker_to_sync_against = self.make_worker_hs(
  1303. "synapse.app.generic_worker", {"worker_name": "synchrotron"}
  1304. )
  1305. # Set presence to BUSY
  1306. self._set_presencestate_with_status_msg(PresenceState.BUSY, status_msg)
  1307. # Perform a sync with a presence state other than busy. This should NOT change
  1308. # our presence status; we only change from busy if we explicitly set it via
  1309. # /presence/*.
  1310. self.get_success(
  1311. worker_to_sync_against.get_presence_handler().user_syncing(
  1312. self.user_id, self.device_id, True, PresenceState.ONLINE
  1313. ),
  1314. by=0.1,
  1315. )
  1316. # Check against the main process that the user's presence did not change.
  1317. state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
  1318. # we should still be busy
  1319. self.assertEqual(state.state, PresenceState.BUSY)
  1320. # Advance such that the device would be discarded if it was not busy,
  1321. # then pump so _handle_timeouts function to called.
  1322. self.reactor.advance(IDLE_TIMER / 1000)
  1323. self.reactor.pump([5])
  1324. # The account should still be busy.
  1325. state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
  1326. self.assertEqual(state.state, PresenceState.BUSY)
  1327. # Ensure that a /presence call can set the user *off* busy.
  1328. self._set_presencestate_with_status_msg(PresenceState.ONLINE, status_msg)
  1329. state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
  1330. self.assertEqual(state.state, PresenceState.ONLINE)
  1331. def _set_presencestate_with_status_msg(
  1332. self, state: str, status_msg: Optional[str]
  1333. ) -> None:
  1334. """Set a PresenceState and status_msg and check the result.
  1335. Args:
  1336. state: The new PresenceState.
  1337. status_msg: Status message that is to be set.
  1338. """
  1339. self.get_success(
  1340. self.presence_handler.set_state(
  1341. self.user_id_obj,
  1342. self.device_id,
  1343. {"presence": state, "status_msg": status_msg},
  1344. )
  1345. )
  1346. new_state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
  1347. self.assertEqual(new_state.state, state)
  1348. self.assertEqual(new_state.status_msg, status_msg)
  1349. @unittest.override_config({"presence": {"enabled": "untracked"}})
  1350. def test_untracked_does_not_idle(self) -> None:
  1351. """Untracked presence should not idle."""
  1352. # Mark user as online, this needs to reach into internals in order to
  1353. # bypass checks.
  1354. state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
  1355. assert isinstance(self.presence_handler, PresenceHandler)
  1356. self.get_success(
  1357. self.presence_handler._update_states(
  1358. [state.copy_and_replace(state=PresenceState.ONLINE)]
  1359. )
  1360. )
  1361. # Ensure the update took.
  1362. state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
  1363. self.assertEqual(state.state, PresenceState.ONLINE)
  1364. # The timeout should not fire and the state should be the same.
  1365. self.reactor.advance(SYNC_ONLINE_TIMEOUT)
  1366. state = self.get_success(self.presence_handler.get_state(self.user_id_obj))
  1367. self.assertEqual(state.state, PresenceState.ONLINE)
  1368. class PresenceFederationQueueTestCase(unittest.HomeserverTestCase):
  1369. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1370. self.presence_handler = hs.get_presence_handler()
  1371. self.clock = hs.get_clock()
  1372. self.instance_name = hs.get_instance_name()
  1373. self.queue = self.presence_handler.get_federation_queue()
  1374. def test_send_and_get(self) -> None:
  1375. state1 = UserPresenceState.default("@user1:test")
  1376. state2 = UserPresenceState.default("@user2:test")
  1377. state3 = UserPresenceState.default("@user3:test")
  1378. prev_token = self.queue.get_current_token(self.instance_name)
  1379. self.get_success(
  1380. self.queue.send_presence_to_destinations(
  1381. (state1, state2), ("dest1", "dest2")
  1382. )
  1383. )
  1384. self.get_success(
  1385. self.queue.send_presence_to_destinations((state3,), ("dest3",))
  1386. )
  1387. now_token = self.queue.get_current_token(self.instance_name)
  1388. rows, upto_token, limited = self.get_success(
  1389. self.queue.get_replication_rows("master", prev_token, now_token, 10)
  1390. )
  1391. self.assertEqual(upto_token, now_token)
  1392. self.assertFalse(limited)
  1393. expected_rows = [
  1394. (1, ("dest1", "@user1:test")),
  1395. (1, ("dest2", "@user1:test")),
  1396. (1, ("dest1", "@user2:test")),
  1397. (1, ("dest2", "@user2:test")),
  1398. (2, ("dest3", "@user3:test")),
  1399. ]
  1400. self.assertCountEqual(rows, expected_rows)
  1401. now_token = self.queue.get_current_token(self.instance_name)
  1402. rows, upto_token, limited = self.get_success(
  1403. self.queue.get_replication_rows("master", upto_token, now_token, 10)
  1404. )
  1405. self.assertEqual(upto_token, now_token)
  1406. self.assertFalse(limited)
  1407. self.assertCountEqual(rows, [])
  1408. def test_send_and_get_split(self) -> None:
  1409. state1 = UserPresenceState.default("@user1:test")
  1410. state2 = UserPresenceState.default("@user2:test")
  1411. state3 = UserPresenceState.default("@user3:test")
  1412. prev_token = self.queue.get_current_token(self.instance_name)
  1413. self.get_success(
  1414. self.queue.send_presence_to_destinations(
  1415. (state1, state2), ("dest1", "dest2")
  1416. )
  1417. )
  1418. now_token = self.queue.get_current_token(self.instance_name)
  1419. self.get_success(
  1420. self.queue.send_presence_to_destinations((state3,), ("dest3",))
  1421. )
  1422. rows, upto_token, limited = self.get_success(
  1423. self.queue.get_replication_rows("master", prev_token, now_token, 10)
  1424. )
  1425. self.assertEqual(upto_token, now_token)
  1426. self.assertFalse(limited)
  1427. expected_rows = [
  1428. (1, ("dest1", "@user1:test")),
  1429. (1, ("dest2", "@user1:test")),
  1430. (1, ("dest1", "@user2:test")),
  1431. (1, ("dest2", "@user2:test")),
  1432. ]
  1433. self.assertCountEqual(rows, expected_rows)
  1434. now_token = self.queue.get_current_token(self.instance_name)
  1435. rows, upto_token, limited = self.get_success(
  1436. self.queue.get_replication_rows("master", upto_token, now_token, 10)
  1437. )
  1438. self.assertEqual(upto_token, now_token)
  1439. self.assertFalse(limited)
  1440. expected_rows = [
  1441. (2, ("dest3", "@user3:test")),
  1442. ]
  1443. self.assertCountEqual(rows, expected_rows)
  1444. def test_clear_queue_all(self) -> None:
  1445. state1 = UserPresenceState.default("@user1:test")
  1446. state2 = UserPresenceState.default("@user2:test")
  1447. state3 = UserPresenceState.default("@user3:test")
  1448. prev_token = self.queue.get_current_token(self.instance_name)
  1449. self.get_success(
  1450. self.queue.send_presence_to_destinations(
  1451. (state1, state2), ("dest1", "dest2")
  1452. )
  1453. )
  1454. self.get_success(
  1455. self.queue.send_presence_to_destinations((state3,), ("dest3",))
  1456. )
  1457. self.reactor.advance(10 * 60 * 1000)
  1458. now_token = self.queue.get_current_token(self.instance_name)
  1459. rows, upto_token, limited = self.get_success(
  1460. self.queue.get_replication_rows("master", prev_token, now_token, 10)
  1461. )
  1462. self.assertEqual(upto_token, now_token)
  1463. self.assertFalse(limited)
  1464. self.assertCountEqual(rows, [])
  1465. prev_token = self.queue.get_current_token(self.instance_name)
  1466. self.get_success(
  1467. self.queue.send_presence_to_destinations(
  1468. (state1, state2), ("dest1", "dest2")
  1469. )
  1470. )
  1471. self.get_success(
  1472. self.queue.send_presence_to_destinations((state3,), ("dest3",))
  1473. )
  1474. now_token = self.queue.get_current_token(self.instance_name)
  1475. rows, upto_token, limited = self.get_success(
  1476. self.queue.get_replication_rows("master", prev_token, now_token, 10)
  1477. )
  1478. self.assertEqual(upto_token, now_token)
  1479. self.assertFalse(limited)
  1480. expected_rows = [
  1481. (3, ("dest1", "@user1:test")),
  1482. (3, ("dest2", "@user1:test")),
  1483. (3, ("dest1", "@user2:test")),
  1484. (3, ("dest2", "@user2:test")),
  1485. (4, ("dest3", "@user3:test")),
  1486. ]
  1487. self.assertCountEqual(rows, expected_rows)
  1488. def test_partially_clear_queue(self) -> None:
  1489. state1 = UserPresenceState.default("@user1:test")
  1490. state2 = UserPresenceState.default("@user2:test")
  1491. state3 = UserPresenceState.default("@user3:test")
  1492. prev_token = self.queue.get_current_token(self.instance_name)
  1493. self.get_success(
  1494. self.queue.send_presence_to_destinations(
  1495. (state1, state2), ("dest1", "dest2")
  1496. )
  1497. )
  1498. self.reactor.advance(2 * 60 * 1000)
  1499. self.get_success(
  1500. self.queue.send_presence_to_destinations((state3,), ("dest3",))
  1501. )
  1502. self.reactor.advance(4 * 60 * 1000)
  1503. now_token = self.queue.get_current_token(self.instance_name)
  1504. rows, upto_token, limited = self.get_success(
  1505. self.queue.get_replication_rows("master", prev_token, now_token, 10)
  1506. )
  1507. self.assertEqual(upto_token, now_token)
  1508. self.assertFalse(limited)
  1509. self.assertCountEqual(rows, [])
  1510. prev_token = self.queue.get_current_token(self.instance_name)
  1511. self.get_success(
  1512. self.queue.send_presence_to_destinations(
  1513. (state1, state2), ("dest1", "dest2")
  1514. )
  1515. )
  1516. self.get_success(
  1517. self.queue.send_presence_to_destinations((state3,), ("dest3",))
  1518. )
  1519. now_token = self.queue.get_current_token(self.instance_name)
  1520. rows, upto_token, limited = self.get_success(
  1521. self.queue.get_replication_rows("master", prev_token, now_token, 10)
  1522. )
  1523. self.assertEqual(upto_token, now_token)
  1524. self.assertFalse(limited)
  1525. expected_rows = [
  1526. (3, ("dest1", "@user1:test")),
  1527. (3, ("dest2", "@user1:test")),
  1528. (3, ("dest1", "@user2:test")),
  1529. (3, ("dest2", "@user2:test")),
  1530. (4, ("dest3", "@user3:test")),
  1531. ]
  1532. self.assertCountEqual(rows, expected_rows)
  1533. class PresenceJoinTestCase(unittest.HomeserverTestCase):
  1534. """Tests remote servers get told about presence of users in the room when
  1535. they join and when new local users join.
  1536. """
  1537. user_id = "@test:server"
  1538. servlets = [room.register_servlets]
  1539. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  1540. hs = self.setup_test_homeserver(
  1541. "server",
  1542. federation_sender=Mock(spec=FederationSender),
  1543. )
  1544. return hs
  1545. def default_config(self) -> JsonDict:
  1546. config = super().default_config()
  1547. # Enable federation sending on the main process.
  1548. config["federation_sender_instances"] = None
  1549. return config
  1550. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1551. self.federation_sender = cast(Mock, hs.get_federation_sender())
  1552. self.event_builder_factory = hs.get_event_builder_factory()
  1553. self.federation_event_handler = hs.get_federation_event_handler()
  1554. self.presence_handler = hs.get_presence_handler()
  1555. # self.event_builder_for_2 = EventBuilderFactory(hs)
  1556. # self.event_builder_for_2.hostname = "test2"
  1557. self.store = hs.get_datastores().main
  1558. self.state = hs.get_state_handler()
  1559. self._event_auth_handler = hs.get_event_auth_handler()
  1560. # We don't actually check signatures in tests, so lets just create a
  1561. # random key to use.
  1562. self.random_signing_key = generate_signing_key("ver")
  1563. def test_remote_joins(self) -> None:
  1564. # We advance time to something that isn't 0, as we use 0 as a special
  1565. # value.
  1566. self.reactor.advance(1000000000000)
  1567. # Create a room with two local users
  1568. room_id = self.helper.create_room_as(self.user_id)
  1569. self.helper.join(room_id, "@test2:server")
  1570. # Mark test2 as online, test will be offline with a last_active of 0
  1571. self.get_success(
  1572. self.presence_handler.set_state(
  1573. UserID.from_string("@test2:server"),
  1574. "dev-1",
  1575. {"presence": PresenceState.ONLINE},
  1576. )
  1577. )
  1578. self.reactor.pump([0]) # Wait for presence updates to be handled
  1579. #
  1580. # Test that a new server gets told about existing presence
  1581. #
  1582. self.federation_sender.reset_mock()
  1583. # Add a new remote server to the room
  1584. self._add_new_user(room_id, "@alice:server2")
  1585. # When new server is joined we send it the local users presence states.
  1586. # We expect to only see user @test2:server, as @test:server is offline
  1587. # and has a zero last_active_ts
  1588. expected_state = self.get_success(
  1589. self.presence_handler.current_state_for_user("@test2:server")
  1590. )
  1591. self.assertEqual(expected_state.state, PresenceState.ONLINE)
  1592. self.federation_sender.send_presence_to_destinations.assert_called_once_with(
  1593. destinations={"server2"}, states=[expected_state]
  1594. )
  1595. #
  1596. # Test that only the new server gets sent presence and not existing servers
  1597. #
  1598. self.federation_sender.reset_mock()
  1599. self._add_new_user(room_id, "@bob:server3")
  1600. self.federation_sender.send_presence_to_destinations.assert_called_once_with(
  1601. destinations={"server3"}, states=[expected_state]
  1602. )
  1603. def test_remote_gets_presence_when_local_user_joins(self) -> None:
  1604. # We advance time to something that isn't 0, as we use 0 as a special
  1605. # value.
  1606. self.reactor.advance(1000000000000)
  1607. # Create a room with one local users
  1608. room_id = self.helper.create_room_as(self.user_id)
  1609. # Mark test as online
  1610. self.get_success(
  1611. self.presence_handler.set_state(
  1612. UserID.from_string("@test:server"),
  1613. "dev-1",
  1614. {"presence": PresenceState.ONLINE},
  1615. )
  1616. )
  1617. # Mark test2 as online, test will be offline with a last_active of 0.
  1618. # Note we don't join them to the room yet
  1619. self.get_success(
  1620. self.presence_handler.set_state(
  1621. UserID.from_string("@test2:server"),
  1622. "dev-1",
  1623. {"presence": PresenceState.ONLINE},
  1624. )
  1625. )
  1626. # Add servers to the room
  1627. self._add_new_user(room_id, "@alice:server2")
  1628. self._add_new_user(room_id, "@bob:server3")
  1629. self.reactor.pump([0]) # Wait for presence updates to be handled
  1630. #
  1631. # Test that when a local join happens remote servers get told about it
  1632. #
  1633. self.federation_sender.reset_mock()
  1634. # Join local user to room
  1635. self.helper.join(room_id, "@test2:server")
  1636. self.reactor.pump([0]) # Wait for presence updates to be handled
  1637. # We expect to only send test2 presence to server2 and server3
  1638. expected_state = self.get_success(
  1639. self.presence_handler.current_state_for_user("@test2:server")
  1640. )
  1641. self.assertEqual(expected_state.state, PresenceState.ONLINE)
  1642. self.federation_sender.send_presence_to_destinations.assert_called_once_with(
  1643. destinations={"server2", "server3"}, states=[expected_state]
  1644. )
  1645. def _add_new_user(self, room_id: str, user_id: str) -> None:
  1646. """Add new user to the room by creating an event and poking the federation API."""
  1647. hostname = get_domain_from_id(user_id)
  1648. room_version = self.get_success(self.store.get_room_version_id(room_id))
  1649. builder = EventBuilder(
  1650. state=self.state,
  1651. event_auth_handler=self._event_auth_handler,
  1652. store=self.store,
  1653. clock=self.clock,
  1654. hostname=hostname,
  1655. signing_key=self.random_signing_key,
  1656. room_version=KNOWN_ROOM_VERSIONS[room_version],
  1657. room_id=room_id,
  1658. type=EventTypes.Member,
  1659. sender=user_id,
  1660. state_key=user_id,
  1661. content={"membership": Membership.JOIN},
  1662. )
  1663. prev_event_ids = self.get_success(
  1664. self.store.get_latest_event_ids_in_room(room_id)
  1665. )
  1666. event = self.get_success(
  1667. builder.build(prev_event_ids=list(prev_event_ids), auth_event_ids=None)
  1668. )
  1669. self.get_success(self.federation_event_handler.on_receive_pdu(hostname, event))
  1670. # Check that it was successfully persisted.
  1671. self.get_success(self.store.get_event(event.event_id))
  1672. self.get_success(self.store.get_event(event.event_id))