test_batching_queue.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. # Copyright 2021 The Matrix.org Foundation C.I.C.
  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 twisted.internet import defer
  15. from synapse.logging.context import make_deferred_yieldable
  16. from synapse.util.batching_queue import (
  17. BatchingQueue,
  18. number_in_flight,
  19. number_of_keys,
  20. number_queued,
  21. )
  22. from tests.server import get_clock
  23. from tests.unittest import TestCase
  24. class BatchingQueueTestCase(TestCase):
  25. def setUp(self):
  26. self.clock, hs_clock = get_clock()
  27. # We ensure that we remove any existing metrics for "test_queue".
  28. try:
  29. number_queued.remove("test_queue")
  30. number_of_keys.remove("test_queue")
  31. number_in_flight.remove("test_queue")
  32. except KeyError:
  33. pass
  34. self._pending_calls = []
  35. self.queue = BatchingQueue("test_queue", hs_clock, self._process_queue)
  36. async def _process_queue(self, values):
  37. d = defer.Deferred()
  38. self._pending_calls.append((values, d))
  39. return await make_deferred_yieldable(d)
  40. def _get_sample_with_name(self, metric, name) -> int:
  41. """For a prometheus metric get the value of the sample that has a
  42. matching "name" label.
  43. """
  44. for sample in metric.collect()[0].samples:
  45. if sample.labels.get("name") == name:
  46. return sample.value
  47. self.fail("Found no matching sample")
  48. def _assert_metrics(self, queued, keys, in_flight):
  49. """Assert that the metrics are correct"""
  50. sample = self._get_sample_with_name(number_queued, self.queue._name)
  51. self.assertEqual(
  52. sample,
  53. queued,
  54. "number_queued",
  55. )
  56. sample = self._get_sample_with_name(number_of_keys, self.queue._name)
  57. self.assertEqual(sample, keys, "number_of_keys")
  58. sample = self._get_sample_with_name(number_in_flight, self.queue._name)
  59. self.assertEqual(
  60. sample,
  61. in_flight,
  62. "number_in_flight",
  63. )
  64. def test_simple(self):
  65. """Tests the basic case of calling `add_to_queue` once and having
  66. `_process_queue` return.
  67. """
  68. self.assertFalse(self._pending_calls)
  69. queue_d = defer.ensureDeferred(self.queue.add_to_queue("foo"))
  70. self._assert_metrics(queued=1, keys=1, in_flight=1)
  71. # The queue should wait a reactor tick before calling the processing
  72. # function.
  73. self.assertFalse(self._pending_calls)
  74. self.assertFalse(queue_d.called)
  75. # We should see a call to `_process_queue` after a reactor tick.
  76. self.clock.pump([0])
  77. self.assertEqual(len(self._pending_calls), 1)
  78. self.assertEqual(self._pending_calls[0][0], ["foo"])
  79. self.assertFalse(queue_d.called)
  80. self._assert_metrics(queued=0, keys=0, in_flight=1)
  81. # Return value of the `_process_queue` should be propagated back.
  82. self._pending_calls.pop()[1].callback("bar")
  83. self.assertEqual(self.successResultOf(queue_d), "bar")
  84. self._assert_metrics(queued=0, keys=0, in_flight=0)
  85. def test_batching(self):
  86. """Test that multiple calls at the same time get batched up into one
  87. call to `_process_queue`.
  88. """
  89. self.assertFalse(self._pending_calls)
  90. queue_d1 = defer.ensureDeferred(self.queue.add_to_queue("foo1"))
  91. queue_d2 = defer.ensureDeferred(self.queue.add_to_queue("foo2"))
  92. self._assert_metrics(queued=2, keys=1, in_flight=2)
  93. self.clock.pump([0])
  94. # We should see only *one* call to `_process_queue`
  95. self.assertEqual(len(self._pending_calls), 1)
  96. self.assertEqual(self._pending_calls[0][0], ["foo1", "foo2"])
  97. self.assertFalse(queue_d1.called)
  98. self.assertFalse(queue_d2.called)
  99. self._assert_metrics(queued=0, keys=0, in_flight=2)
  100. # Return value of the `_process_queue` should be propagated back to both.
  101. self._pending_calls.pop()[1].callback("bar")
  102. self.assertEqual(self.successResultOf(queue_d1), "bar")
  103. self.assertEqual(self.successResultOf(queue_d2), "bar")
  104. self._assert_metrics(queued=0, keys=0, in_flight=0)
  105. def test_queuing(self):
  106. """Test that we queue up requests while a `_process_queue` is being
  107. called.
  108. """
  109. self.assertFalse(self._pending_calls)
  110. queue_d1 = defer.ensureDeferred(self.queue.add_to_queue("foo1"))
  111. self.clock.pump([0])
  112. self.assertEqual(len(self._pending_calls), 1)
  113. # We queue up work after the process function has been called, testing
  114. # that they get correctly queued up.
  115. queue_d2 = defer.ensureDeferred(self.queue.add_to_queue("foo2"))
  116. queue_d3 = defer.ensureDeferred(self.queue.add_to_queue("foo3"))
  117. # We should see only *one* call to `_process_queue`
  118. self.assertEqual(len(self._pending_calls), 1)
  119. self.assertEqual(self._pending_calls[0][0], ["foo1"])
  120. self.assertFalse(queue_d1.called)
  121. self.assertFalse(queue_d2.called)
  122. self.assertFalse(queue_d3.called)
  123. self._assert_metrics(queued=2, keys=1, in_flight=3)
  124. # Return value of the `_process_queue` should be propagated back to the
  125. # first.
  126. self._pending_calls.pop()[1].callback("bar1")
  127. self.assertEqual(self.successResultOf(queue_d1), "bar1")
  128. self.assertFalse(queue_d2.called)
  129. self.assertFalse(queue_d3.called)
  130. self._assert_metrics(queued=2, keys=1, in_flight=2)
  131. # We should now see a second call to `_process_queue`
  132. self.clock.pump([0])
  133. self.assertEqual(len(self._pending_calls), 1)
  134. self.assertEqual(self._pending_calls[0][0], ["foo2", "foo3"])
  135. self.assertFalse(queue_d2.called)
  136. self.assertFalse(queue_d3.called)
  137. self._assert_metrics(queued=0, keys=0, in_flight=2)
  138. # Return value of the `_process_queue` should be propagated back to the
  139. # second.
  140. self._pending_calls.pop()[1].callback("bar2")
  141. self.assertEqual(self.successResultOf(queue_d2), "bar2")
  142. self.assertEqual(self.successResultOf(queue_d3), "bar2")
  143. self._assert_metrics(queued=0, keys=0, in_flight=0)
  144. def test_different_keys(self):
  145. """Test that calls to different keys get processed in parallel."""
  146. self.assertFalse(self._pending_calls)
  147. queue_d1 = defer.ensureDeferred(self.queue.add_to_queue("foo1", key=1))
  148. self.clock.pump([0])
  149. queue_d2 = defer.ensureDeferred(self.queue.add_to_queue("foo2", key=2))
  150. self.clock.pump([0])
  151. # We queue up another item with key=2 to check that we will keep taking
  152. # things off the queue.
  153. queue_d3 = defer.ensureDeferred(self.queue.add_to_queue("foo3", key=2))
  154. # We should see two calls to `_process_queue`
  155. self.assertEqual(len(self._pending_calls), 2)
  156. self.assertEqual(self._pending_calls[0][0], ["foo1"])
  157. self.assertEqual(self._pending_calls[1][0], ["foo2"])
  158. self.assertFalse(queue_d1.called)
  159. self.assertFalse(queue_d2.called)
  160. self.assertFalse(queue_d3.called)
  161. self._assert_metrics(queued=1, keys=1, in_flight=3)
  162. # Return value of the `_process_queue` should be propagated back to the
  163. # first.
  164. self._pending_calls.pop(0)[1].callback("bar1")
  165. self.assertEqual(self.successResultOf(queue_d1), "bar1")
  166. self.assertFalse(queue_d2.called)
  167. self.assertFalse(queue_d3.called)
  168. self._assert_metrics(queued=1, keys=1, in_flight=2)
  169. # Return value of the `_process_queue` should be propagated back to the
  170. # second.
  171. self._pending_calls.pop()[1].callback("bar2")
  172. self.assertEqual(self.successResultOf(queue_d2), "bar2")
  173. self.assertFalse(queue_d3.called)
  174. # We should now see a call `_pending_calls` for `foo3`
  175. self.clock.pump([0])
  176. self.assertEqual(len(self._pending_calls), 1)
  177. self.assertEqual(self._pending_calls[0][0], ["foo3"])
  178. self.assertFalse(queue_d3.called)
  179. self._assert_metrics(queued=0, keys=0, in_flight=1)
  180. # Return value of the `_process_queue` should be propagated back to the
  181. # third deferred.
  182. self._pending_calls.pop()[1].callback("bar4")
  183. self.assertEqual(self.successResultOf(queue_d3), "bar4")
  184. self._assert_metrics(queued=0, keys=0, in_flight=0)