test_scheduler.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. # Copyright 2015, 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. from typing import List, Optional, Sequence, Tuple, cast
  15. from unittest.mock import Mock
  16. from typing_extensions import TypeAlias
  17. from twisted.internet import defer
  18. from twisted.test.proto_helpers import MemoryReactor
  19. from synapse.appservice import (
  20. ApplicationService,
  21. ApplicationServiceState,
  22. TransactionOneTimeKeysCount,
  23. TransactionUnusedFallbackKeys,
  24. )
  25. from synapse.appservice.scheduler import (
  26. ApplicationServiceScheduler,
  27. _Recoverer,
  28. _TransactionController,
  29. )
  30. from synapse.events import EventBase
  31. from synapse.logging.context import make_deferred_yieldable
  32. from synapse.server import HomeServer
  33. from synapse.types import DeviceListUpdates, JsonDict
  34. from synapse.util import Clock
  35. from tests import unittest
  36. from tests.test_utils import simple_async_mock
  37. from ..utils import MockClock
  38. class ApplicationServiceSchedulerTransactionCtrlTestCase(unittest.TestCase):
  39. def setUp(self) -> None:
  40. self.clock = MockClock()
  41. self.store = Mock()
  42. self.as_api = Mock()
  43. self.recoverer = Mock()
  44. self.recoverer_fn = Mock(return_value=self.recoverer)
  45. self.txnctrl = _TransactionController(
  46. clock=cast(Clock, self.clock), store=self.store, as_api=self.as_api
  47. )
  48. self.txnctrl.RECOVERER_CLASS = self.recoverer_fn
  49. def test_single_service_up_txn_sent(self) -> None:
  50. # Test: The AS is up and the txn is successfully sent.
  51. service = Mock()
  52. events = [Mock(), Mock()]
  53. txn_id = "foobar"
  54. txn = Mock(id=txn_id, service=service, events=events)
  55. # mock methods
  56. self.store.get_appservice_state = simple_async_mock(ApplicationServiceState.UP)
  57. txn.send = simple_async_mock(True)
  58. txn.complete = simple_async_mock(True)
  59. self.store.create_appservice_txn = simple_async_mock(txn)
  60. # actual call
  61. self.successResultOf(defer.ensureDeferred(self.txnctrl.send(service, events)))
  62. self.store.create_appservice_txn.assert_called_once_with(
  63. service=service,
  64. events=events,
  65. ephemeral=[],
  66. to_device_messages=[], # txn made and saved
  67. one_time_keys_count={},
  68. unused_fallback_keys={},
  69. device_list_summary=DeviceListUpdates(),
  70. )
  71. self.assertEqual(0, len(self.txnctrl.recoverers)) # no recoverer made
  72. txn.complete.assert_called_once_with(self.store) # txn completed
  73. def test_single_service_down(self) -> None:
  74. # Test: The AS is down so it shouldn't push; Recoverers will do it.
  75. # It should still make a transaction though.
  76. service = Mock()
  77. events = [Mock(), Mock()]
  78. txn = Mock(id="idhere", service=service, events=events)
  79. self.store.get_appservice_state = simple_async_mock(
  80. ApplicationServiceState.DOWN
  81. )
  82. self.store.create_appservice_txn = simple_async_mock(txn)
  83. # actual call
  84. self.successResultOf(defer.ensureDeferred(self.txnctrl.send(service, events)))
  85. self.store.create_appservice_txn.assert_called_once_with(
  86. service=service,
  87. events=events,
  88. ephemeral=[],
  89. to_device_messages=[], # txn made and saved
  90. one_time_keys_count={},
  91. unused_fallback_keys={},
  92. device_list_summary=DeviceListUpdates(),
  93. )
  94. self.assertEqual(0, txn.send.call_count) # txn not sent though
  95. self.assertEqual(0, txn.complete.call_count) # or completed
  96. def test_single_service_up_txn_not_sent(self) -> None:
  97. # Test: The AS is up and the txn is not sent. A Recoverer is made and
  98. # started.
  99. service = Mock()
  100. events = [Mock(), Mock()]
  101. txn_id = "foobar"
  102. txn = Mock(id=txn_id, service=service, events=events)
  103. # mock methods
  104. self.store.get_appservice_state = simple_async_mock(ApplicationServiceState.UP)
  105. self.store.set_appservice_state = simple_async_mock(True)
  106. txn.send = simple_async_mock(False) # fails to send
  107. self.store.create_appservice_txn = simple_async_mock(txn)
  108. # actual call
  109. self.successResultOf(defer.ensureDeferred(self.txnctrl.send(service, events)))
  110. self.store.create_appservice_txn.assert_called_once_with(
  111. service=service,
  112. events=events,
  113. ephemeral=[],
  114. to_device_messages=[],
  115. one_time_keys_count={},
  116. unused_fallback_keys={},
  117. device_list_summary=DeviceListUpdates(),
  118. )
  119. self.assertEqual(1, self.recoverer_fn.call_count) # recoverer made
  120. self.assertEqual(1, self.recoverer.recover.call_count) # and invoked
  121. self.assertEqual(1, len(self.txnctrl.recoverers)) # and stored
  122. self.assertEqual(0, txn.complete.call_count) # txn not completed
  123. self.store.set_appservice_state.assert_called_once_with(
  124. service, ApplicationServiceState.DOWN # service marked as down
  125. )
  126. class ApplicationServiceSchedulerRecovererTestCase(unittest.TestCase):
  127. def setUp(self) -> None:
  128. self.clock = MockClock()
  129. self.as_api = Mock()
  130. self.store = Mock()
  131. self.service = Mock()
  132. self.callback = simple_async_mock()
  133. self.recoverer = _Recoverer(
  134. clock=cast(Clock, self.clock),
  135. as_api=self.as_api,
  136. store=self.store,
  137. service=self.service,
  138. callback=self.callback,
  139. )
  140. def test_recover_single_txn(self) -> None:
  141. txn = Mock()
  142. # return one txn to send, then no more old txns
  143. txns = [txn, None]
  144. def take_txn(
  145. *args: object, **kwargs: object
  146. ) -> "defer.Deferred[Optional[Mock]]":
  147. return defer.succeed(txns.pop(0))
  148. self.store.get_oldest_unsent_txn = Mock(side_effect=take_txn)
  149. self.recoverer.recover()
  150. # shouldn't have called anything prior to waiting for exp backoff
  151. self.assertEqual(0, self.store.get_oldest_unsent_txn.call_count)
  152. txn.send = simple_async_mock(True)
  153. txn.complete = simple_async_mock(None)
  154. # wait for exp backoff
  155. self.clock.advance_time(2)
  156. self.assertEqual(1, txn.send.call_count)
  157. self.assertEqual(1, txn.complete.call_count)
  158. # 2 because it needs to get None to know there are no more txns
  159. self.assertEqual(2, self.store.get_oldest_unsent_txn.call_count)
  160. self.callback.assert_called_once_with(self.recoverer)
  161. self.assertEqual(self.recoverer.service, self.service)
  162. def test_recover_retry_txn(self) -> None:
  163. txn = Mock()
  164. txns = [txn, None]
  165. pop_txn = False
  166. def take_txn(
  167. *args: object, **kwargs: object
  168. ) -> "defer.Deferred[Optional[Mock]]":
  169. if pop_txn:
  170. return defer.succeed(txns.pop(0))
  171. else:
  172. return defer.succeed(txn)
  173. self.store.get_oldest_unsent_txn = Mock(side_effect=take_txn)
  174. self.recoverer.recover()
  175. self.assertEqual(0, self.store.get_oldest_unsent_txn.call_count)
  176. txn.send = simple_async_mock(False)
  177. txn.complete = simple_async_mock(None)
  178. self.clock.advance_time(2)
  179. self.assertEqual(1, txn.send.call_count)
  180. self.assertEqual(0, txn.complete.call_count)
  181. self.assertEqual(0, self.callback.call_count)
  182. self.clock.advance_time(4)
  183. self.assertEqual(2, txn.send.call_count)
  184. self.assertEqual(0, txn.complete.call_count)
  185. self.assertEqual(0, self.callback.call_count)
  186. self.clock.advance_time(8)
  187. self.assertEqual(3, txn.send.call_count)
  188. self.assertEqual(0, txn.complete.call_count)
  189. self.assertEqual(0, self.callback.call_count)
  190. txn.send = simple_async_mock(True) # successfully send the txn
  191. pop_txn = True # returns the txn the first time, then no more.
  192. self.clock.advance_time(16)
  193. self.assertEqual(1, txn.send.call_count) # new mock reset call count
  194. self.assertEqual(1, txn.complete.call_count)
  195. self.callback.assert_called_once_with(self.recoverer)
  196. # Corresponds to synapse.appservice.scheduler._TransactionController.send
  197. TxnCtrlArgs: TypeAlias = """
  198. defer.Deferred[
  199. Tuple[
  200. ApplicationService,
  201. Sequence[EventBase],
  202. Optional[List[JsonDict]],
  203. Optional[List[JsonDict]],
  204. Optional[TransactionOneTimeKeysCount],
  205. Optional[TransactionUnusedFallbackKeys],
  206. Optional[DeviceListUpdates],
  207. ]
  208. ]
  209. """
  210. class ApplicationServiceSchedulerQueuerTestCase(unittest.HomeserverTestCase):
  211. def prepare(self, reactor: "MemoryReactor", clock: Clock, hs: HomeServer) -> None:
  212. self.scheduler = ApplicationServiceScheduler(hs)
  213. self.txn_ctrl = Mock()
  214. self.txn_ctrl.send = simple_async_mock()
  215. # Replace instantiated _TransactionController instances with our Mock
  216. self.scheduler.txn_ctrl = self.txn_ctrl
  217. self.scheduler.queuer.txn_ctrl = self.txn_ctrl
  218. def test_send_single_event_no_queue(self) -> None:
  219. # Expect the event to be sent immediately.
  220. service = Mock(id=4)
  221. event = Mock()
  222. self.scheduler.enqueue_for_appservice(service, events=[event])
  223. self.txn_ctrl.send.assert_called_once_with(
  224. service, [event], [], [], None, None, DeviceListUpdates()
  225. )
  226. def test_send_single_event_with_queue(self) -> None:
  227. d: TxnCtrlArgs = defer.Deferred()
  228. self.txn_ctrl.send = Mock(return_value=make_deferred_yieldable(d))
  229. service = Mock(id=4)
  230. event = Mock(event_id="first")
  231. event2 = Mock(event_id="second")
  232. event3 = Mock(event_id="third")
  233. # Send an event and don't resolve it just yet.
  234. self.scheduler.enqueue_for_appservice(service, events=[event])
  235. # Send more events: expect send() to NOT be called multiple times.
  236. # (call enqueue_for_appservice multiple times deliberately)
  237. self.scheduler.enqueue_for_appservice(service, events=[event2])
  238. self.scheduler.enqueue_for_appservice(service, events=[event3])
  239. self.txn_ctrl.send.assert_called_with(
  240. service, [event], [], [], None, None, DeviceListUpdates()
  241. )
  242. self.assertEqual(1, self.txn_ctrl.send.call_count)
  243. # Resolve the send event: expect the queued events to be sent
  244. d.callback(service)
  245. self.txn_ctrl.send.assert_called_with(
  246. service, [event2, event3], [], [], None, None, DeviceListUpdates()
  247. )
  248. self.assertEqual(2, self.txn_ctrl.send.call_count)
  249. def test_multiple_service_queues(self) -> None:
  250. # Tests that each service has its own queue, and that they don't block
  251. # on each other.
  252. srv1 = Mock(id=4)
  253. srv_1_defer: "defer.Deferred[EventBase]" = defer.Deferred()
  254. srv_1_event = Mock(event_id="srv1a")
  255. srv_1_event2 = Mock(event_id="srv1b")
  256. srv2 = Mock(id=6)
  257. srv_2_defer: "defer.Deferred[EventBase]" = defer.Deferred()
  258. srv_2_event = Mock(event_id="srv2a")
  259. srv_2_event2 = Mock(event_id="srv2b")
  260. send_return_list = [srv_1_defer, srv_2_defer]
  261. def do_send(*args: object, **kwargs: object) -> "defer.Deferred[EventBase]":
  262. return make_deferred_yieldable(send_return_list.pop(0))
  263. self.txn_ctrl.send = Mock(side_effect=do_send)
  264. # send events for different ASes and make sure they are sent
  265. self.scheduler.enqueue_for_appservice(srv1, events=[srv_1_event])
  266. self.scheduler.enqueue_for_appservice(srv1, events=[srv_1_event2])
  267. self.txn_ctrl.send.assert_called_with(
  268. srv1, [srv_1_event], [], [], None, None, DeviceListUpdates()
  269. )
  270. self.scheduler.enqueue_for_appservice(srv2, events=[srv_2_event])
  271. self.scheduler.enqueue_for_appservice(srv2, events=[srv_2_event2])
  272. self.txn_ctrl.send.assert_called_with(
  273. srv2, [srv_2_event], [], [], None, None, DeviceListUpdates()
  274. )
  275. # make sure callbacks for a service only send queued events for THAT
  276. # service
  277. srv_2_defer.callback(srv2)
  278. self.txn_ctrl.send.assert_called_with(
  279. srv2, [srv_2_event2], [], [], None, None, DeviceListUpdates()
  280. )
  281. self.assertEqual(3, self.txn_ctrl.send.call_count)
  282. def test_send_large_txns(self) -> None:
  283. srv_1_defer: "defer.Deferred[EventBase]" = defer.Deferred()
  284. srv_2_defer: "defer.Deferred[EventBase]" = defer.Deferred()
  285. send_return_list = [srv_1_defer, srv_2_defer]
  286. def do_send(*args: object, **kwargs: object) -> "defer.Deferred[EventBase]":
  287. return make_deferred_yieldable(send_return_list.pop(0))
  288. self.txn_ctrl.send = Mock(side_effect=do_send)
  289. service = Mock(id=4, name="service")
  290. event_list = [Mock(name="event%i" % (i + 1)) for i in range(200)]
  291. for event in event_list:
  292. self.scheduler.enqueue_for_appservice(service, [event], [])
  293. # Expect the first event to be sent immediately.
  294. self.txn_ctrl.send.assert_called_with(
  295. service, [event_list[0]], [], [], None, None, DeviceListUpdates()
  296. )
  297. srv_1_defer.callback(service)
  298. # Then send the next 100 events
  299. self.txn_ctrl.send.assert_called_with(
  300. service, event_list[1:101], [], [], None, None, DeviceListUpdates()
  301. )
  302. srv_2_defer.callback(service)
  303. # Then the final 99 events
  304. self.txn_ctrl.send.assert_called_with(
  305. service, event_list[101:], [], [], None, None, DeviceListUpdates()
  306. )
  307. self.assertEqual(3, self.txn_ctrl.send.call_count)
  308. def test_send_single_ephemeral_no_queue(self) -> None:
  309. # Expect the event to be sent immediately.
  310. service = Mock(id=4, name="service")
  311. event_list = [Mock(name="event")]
  312. self.scheduler.enqueue_for_appservice(service, ephemeral=event_list)
  313. self.txn_ctrl.send.assert_called_once_with(
  314. service, [], event_list, [], None, None, DeviceListUpdates()
  315. )
  316. def test_send_multiple_ephemeral_no_queue(self) -> None:
  317. # Expect the event to be sent immediately.
  318. service = Mock(id=4, name="service")
  319. event_list = [Mock(name="event1"), Mock(name="event2"), Mock(name="event3")]
  320. self.scheduler.enqueue_for_appservice(service, ephemeral=event_list)
  321. self.txn_ctrl.send.assert_called_once_with(
  322. service, [], event_list, [], None, None, DeviceListUpdates()
  323. )
  324. def test_send_single_ephemeral_with_queue(self) -> None:
  325. d: TxnCtrlArgs = defer.Deferred()
  326. self.txn_ctrl.send = Mock(return_value=make_deferred_yieldable(d))
  327. service = Mock(id=4)
  328. event_list_1 = [Mock(event_id="event1"), Mock(event_id="event2")]
  329. event_list_2 = [Mock(event_id="event3"), Mock(event_id="event4")]
  330. event_list_3 = [Mock(event_id="event5"), Mock(event_id="event6")]
  331. # Send an event and don't resolve it just yet.
  332. self.scheduler.enqueue_for_appservice(service, ephemeral=event_list_1)
  333. # Send more events: expect send() to NOT be called multiple times.
  334. self.scheduler.enqueue_for_appservice(service, ephemeral=event_list_2)
  335. self.scheduler.enqueue_for_appservice(service, ephemeral=event_list_3)
  336. self.txn_ctrl.send.assert_called_with(
  337. service, [], event_list_1, [], None, None, DeviceListUpdates()
  338. )
  339. self.assertEqual(1, self.txn_ctrl.send.call_count)
  340. # Resolve txn_ctrl.send
  341. d.callback(service)
  342. # Expect the queued events to be sent
  343. self.txn_ctrl.send.assert_called_with(
  344. service,
  345. [],
  346. event_list_2 + event_list_3,
  347. [],
  348. None,
  349. None,
  350. DeviceListUpdates(),
  351. )
  352. self.assertEqual(2, self.txn_ctrl.send.call_count)
  353. def test_send_large_txns_ephemeral(self) -> None:
  354. d: TxnCtrlArgs = defer.Deferred()
  355. self.txn_ctrl.send = Mock(return_value=make_deferred_yieldable(d))
  356. # Expect the event to be sent immediately.
  357. service = Mock(id=4, name="service")
  358. first_chunk = [Mock(name="event%i" % (i + 1)) for i in range(100)]
  359. second_chunk = [Mock(name="event%i" % (i + 101)) for i in range(50)]
  360. event_list = first_chunk + second_chunk
  361. self.scheduler.enqueue_for_appservice(service, ephemeral=event_list)
  362. self.txn_ctrl.send.assert_called_once_with(
  363. service, [], first_chunk, [], None, None, DeviceListUpdates()
  364. )
  365. d.callback(service)
  366. self.txn_ctrl.send.assert_called_with(
  367. service, [], second_chunk, [], None, None, DeviceListUpdates()
  368. )
  369. self.assertEqual(2, self.txn_ctrl.send.call_count)