test_scheduler.py 17 KB

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