test_async_helpers.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. # Copyright 2019 New Vector 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 traceback
  15. from parameterized import parameterized_class
  16. from twisted.internet import defer
  17. from twisted.internet.defer import CancelledError, Deferred, ensureDeferred
  18. from twisted.internet.task import Clock
  19. from twisted.python.failure import Failure
  20. from synapse.logging.context import (
  21. SENTINEL_CONTEXT,
  22. LoggingContext,
  23. PreserveLoggingContext,
  24. current_context,
  25. make_deferred_yieldable,
  26. )
  27. from synapse.util.async_helpers import (
  28. ObservableDeferred,
  29. concurrently_execute,
  30. delay_cancellation,
  31. stop_cancellation,
  32. timeout_deferred,
  33. )
  34. from tests.unittest import TestCase
  35. class ObservableDeferredTest(TestCase):
  36. def test_succeed(self):
  37. origin_d = Deferred()
  38. observable = ObservableDeferred(origin_d)
  39. observer1 = observable.observe()
  40. observer2 = observable.observe()
  41. self.assertFalse(observer1.called)
  42. self.assertFalse(observer2.called)
  43. # check the first observer is called first
  44. def check_called_first(res):
  45. self.assertFalse(observer2.called)
  46. return res
  47. observer1.addBoth(check_called_first)
  48. # store the results
  49. results = [None, None]
  50. def check_val(res, idx):
  51. results[idx] = res
  52. return res
  53. observer1.addCallback(check_val, 0)
  54. observer2.addCallback(check_val, 1)
  55. origin_d.callback(123)
  56. self.assertEqual(results[0], 123, "observer 1 callback result")
  57. self.assertEqual(results[1], 123, "observer 2 callback result")
  58. def test_failure(self):
  59. origin_d = Deferred()
  60. observable = ObservableDeferred(origin_d, consumeErrors=True)
  61. observer1 = observable.observe()
  62. observer2 = observable.observe()
  63. self.assertFalse(observer1.called)
  64. self.assertFalse(observer2.called)
  65. # check the first observer is called first
  66. def check_called_first(res):
  67. self.assertFalse(observer2.called)
  68. return res
  69. observer1.addBoth(check_called_first)
  70. # store the results
  71. results = [None, None]
  72. def check_val(res, idx):
  73. results[idx] = res
  74. return None
  75. observer1.addErrback(check_val, 0)
  76. observer2.addErrback(check_val, 1)
  77. try:
  78. raise Exception("gah!")
  79. except Exception as e:
  80. origin_d.errback(e)
  81. self.assertEqual(str(results[0].value), "gah!", "observer 1 errback result")
  82. self.assertEqual(str(results[1].value), "gah!", "observer 2 errback result")
  83. def test_cancellation(self):
  84. """Test that cancelling an observer does not affect other observers."""
  85. origin_d: "Deferred[int]" = Deferred()
  86. observable = ObservableDeferred(origin_d, consumeErrors=True)
  87. observer1 = observable.observe()
  88. observer2 = observable.observe()
  89. observer3 = observable.observe()
  90. self.assertFalse(observer1.called)
  91. self.assertFalse(observer2.called)
  92. self.assertFalse(observer3.called)
  93. # cancel the second observer
  94. observer2.cancel()
  95. self.assertFalse(observer1.called)
  96. self.failureResultOf(observer2, CancelledError)
  97. self.assertFalse(observer3.called)
  98. # other observers resolve as normal
  99. origin_d.callback(123)
  100. self.assertEqual(observer1.result, 123, "observer 1 callback result")
  101. self.assertEqual(observer3.result, 123, "observer 3 callback result")
  102. # additional observers resolve as normal
  103. observer4 = observable.observe()
  104. self.assertEqual(observer4.result, 123, "observer 4 callback result")
  105. class TimeoutDeferredTest(TestCase):
  106. def setUp(self):
  107. self.clock = Clock()
  108. def test_times_out(self):
  109. """Basic test case that checks that the original deferred is cancelled and that
  110. the timing-out deferred is errbacked
  111. """
  112. cancelled = [False]
  113. def canceller(_d):
  114. cancelled[0] = True
  115. non_completing_d = Deferred(canceller)
  116. timing_out_d = timeout_deferred(non_completing_d, 1.0, self.clock)
  117. self.assertNoResult(timing_out_d)
  118. self.assertFalse(cancelled[0], "deferred was cancelled prematurely")
  119. self.clock.pump((1.0,))
  120. self.assertTrue(cancelled[0], "deferred was not cancelled by timeout")
  121. self.failureResultOf(timing_out_d, defer.TimeoutError)
  122. def test_times_out_when_canceller_throws(self):
  123. """Test that we have successfully worked around
  124. https://twistedmatrix.com/trac/ticket/9534"""
  125. def canceller(_d):
  126. raise Exception("can't cancel this deferred")
  127. non_completing_d = Deferred(canceller)
  128. timing_out_d = timeout_deferred(non_completing_d, 1.0, self.clock)
  129. self.assertNoResult(timing_out_d)
  130. self.clock.pump((1.0,))
  131. self.failureResultOf(timing_out_d, defer.TimeoutError)
  132. def test_logcontext_is_preserved_on_cancellation(self):
  133. blocking_was_cancelled = [False]
  134. @defer.inlineCallbacks
  135. def blocking():
  136. non_completing_d = Deferred()
  137. with PreserveLoggingContext():
  138. try:
  139. yield non_completing_d
  140. except CancelledError:
  141. blocking_was_cancelled[0] = True
  142. raise
  143. with LoggingContext("one") as context_one:
  144. # the errbacks should be run in the test logcontext
  145. def errback(res, deferred_name):
  146. self.assertIs(
  147. current_context(),
  148. context_one,
  149. "errback %s run in unexpected logcontext %s"
  150. % (deferred_name, current_context()),
  151. )
  152. return res
  153. original_deferred = blocking()
  154. original_deferred.addErrback(errback, "orig")
  155. timing_out_d = timeout_deferred(original_deferred, 1.0, self.clock)
  156. self.assertNoResult(timing_out_d)
  157. self.assertIs(current_context(), SENTINEL_CONTEXT)
  158. timing_out_d.addErrback(errback, "timingout")
  159. self.clock.pump((1.0,))
  160. self.assertTrue(
  161. blocking_was_cancelled[0], "non-completing deferred was not cancelled"
  162. )
  163. self.failureResultOf(timing_out_d, defer.TimeoutError)
  164. self.assertIs(current_context(), context_one)
  165. class _TestException(Exception):
  166. pass
  167. class ConcurrentlyExecuteTest(TestCase):
  168. def test_limits_runners(self):
  169. """If we have more tasks than runners, we should get the limit of runners"""
  170. started = 0
  171. waiters = []
  172. processed = []
  173. async def callback(v):
  174. # when we first enter, bump the start count
  175. nonlocal started
  176. started += 1
  177. # record the fact we got an item
  178. processed.append(v)
  179. # wait for the goahead before returning
  180. d2 = Deferred()
  181. waiters.append(d2)
  182. await d2
  183. # set it going
  184. d2 = ensureDeferred(concurrently_execute(callback, [1, 2, 3, 4, 5], 3))
  185. # check we got exactly 3 processes
  186. self.assertEqual(started, 3)
  187. self.assertEqual(len(waiters), 3)
  188. # let one finish
  189. waiters.pop().callback(0)
  190. # ... which should start another
  191. self.assertEqual(started, 4)
  192. self.assertEqual(len(waiters), 3)
  193. # we still shouldn't be done
  194. self.assertNoResult(d2)
  195. # finish the job
  196. while waiters:
  197. waiters.pop().callback(0)
  198. # check everything got done
  199. self.assertEqual(started, 5)
  200. self.assertCountEqual(processed, [1, 2, 3, 4, 5])
  201. self.successResultOf(d2)
  202. def test_preserves_stacktraces(self):
  203. """Test that the stacktrace from an exception thrown in the callback is preserved"""
  204. d1 = Deferred()
  205. async def callback(v):
  206. # alas, this doesn't work at all without an await here
  207. await d1
  208. raise _TestException("bah")
  209. async def caller():
  210. try:
  211. await concurrently_execute(callback, [1], 2)
  212. except _TestException as e:
  213. tb = traceback.extract_tb(e.__traceback__)
  214. # we expect to see "caller", "concurrently_execute" and "callback".
  215. self.assertEqual(tb[0].name, "caller")
  216. self.assertEqual(tb[1].name, "concurrently_execute")
  217. self.assertEqual(tb[-1].name, "callback")
  218. else:
  219. self.fail("No exception thrown")
  220. d2 = ensureDeferred(caller())
  221. d1.callback(0)
  222. self.successResultOf(d2)
  223. def test_preserves_stacktraces_on_preformed_failure(self):
  224. """Test that the stacktrace on a Failure returned by the callback is preserved"""
  225. d1 = Deferred()
  226. f = Failure(_TestException("bah"))
  227. async def callback(v):
  228. # alas, this doesn't work at all without an await here
  229. await d1
  230. await defer.fail(f)
  231. async def caller():
  232. try:
  233. await concurrently_execute(callback, [1], 2)
  234. except _TestException as e:
  235. tb = traceback.extract_tb(e.__traceback__)
  236. # we expect to see "caller", "concurrently_execute", "callback",
  237. # and some magic from inside ensureDeferred that happens when .fail
  238. # is called.
  239. self.assertEqual(tb[0].name, "caller")
  240. self.assertEqual(tb[1].name, "concurrently_execute")
  241. self.assertEqual(tb[-2].name, "callback")
  242. else:
  243. self.fail("No exception thrown")
  244. d2 = ensureDeferred(caller())
  245. d1.callback(0)
  246. self.successResultOf(d2)
  247. @parameterized_class(
  248. ("wrapper",),
  249. [("stop_cancellation",), ("delay_cancellation",)],
  250. )
  251. class CancellationWrapperTests(TestCase):
  252. """Common tests for the `stop_cancellation` and `delay_cancellation` functions."""
  253. wrapper: str
  254. def wrap_deferred(self, deferred: "Deferred[str]") -> "Deferred[str]":
  255. if self.wrapper == "stop_cancellation":
  256. return stop_cancellation(deferred)
  257. elif self.wrapper == "delay_cancellation":
  258. return delay_cancellation(deferred)
  259. else:
  260. raise ValueError(f"Unsupported wrapper type: {self.wrapper}")
  261. def test_succeed(self):
  262. """Test that the new `Deferred` receives the result."""
  263. deferred: "Deferred[str]" = Deferred()
  264. wrapper_deferred = self.wrap_deferred(deferred)
  265. # Success should propagate through.
  266. deferred.callback("success")
  267. self.assertTrue(wrapper_deferred.called)
  268. self.assertEqual("success", self.successResultOf(wrapper_deferred))
  269. def test_failure(self):
  270. """Test that the new `Deferred` receives the `Failure`."""
  271. deferred: "Deferred[str]" = Deferred()
  272. wrapper_deferred = self.wrap_deferred(deferred)
  273. # Failure should propagate through.
  274. deferred.errback(ValueError("abc"))
  275. self.assertTrue(wrapper_deferred.called)
  276. self.failureResultOf(wrapper_deferred, ValueError)
  277. self.assertIsNone(deferred.result, "`Failure` was not consumed")
  278. class StopCancellationTests(TestCase):
  279. """Tests for the `stop_cancellation` function."""
  280. def test_cancellation(self):
  281. """Test that cancellation of the new `Deferred` leaves the original running."""
  282. deferred: "Deferred[str]" = Deferred()
  283. wrapper_deferred = stop_cancellation(deferred)
  284. # Cancel the new `Deferred`.
  285. wrapper_deferred.cancel()
  286. self.assertTrue(wrapper_deferred.called)
  287. self.failureResultOf(wrapper_deferred, CancelledError)
  288. self.assertFalse(
  289. deferred.called, "Original `Deferred` was unexpectedly cancelled"
  290. )
  291. # Now make the original `Deferred` fail.
  292. # The `Failure` must be consumed, otherwise unwanted tracebacks will be printed
  293. # in logs.
  294. deferred.errback(ValueError("abc"))
  295. self.assertIsNone(deferred.result, "`Failure` was not consumed")
  296. class DelayCancellationTests(TestCase):
  297. """Tests for the `delay_cancellation` function."""
  298. def test_cancellation(self):
  299. """Test that cancellation of the new `Deferred` waits for the original."""
  300. deferred: "Deferred[str]" = Deferred()
  301. wrapper_deferred = delay_cancellation(deferred)
  302. # Cancel the new `Deferred`.
  303. wrapper_deferred.cancel()
  304. self.assertNoResult(wrapper_deferred)
  305. self.assertFalse(
  306. deferred.called, "Original `Deferred` was unexpectedly cancelled"
  307. )
  308. # Now make the original `Deferred` fail.
  309. # The `Failure` must be consumed, otherwise unwanted tracebacks will be printed
  310. # in logs.
  311. deferred.errback(ValueError("abc"))
  312. self.assertIsNone(deferred.result, "`Failure` was not consumed")
  313. # Now that the original `Deferred` has failed, we should get a `CancelledError`.
  314. self.failureResultOf(wrapper_deferred, CancelledError)
  315. def test_suppresses_second_cancellation(self):
  316. """Test that a second cancellation is suppressed.
  317. Identical to `test_cancellation` except the new `Deferred` is cancelled twice.
  318. """
  319. deferred: "Deferred[str]" = Deferred()
  320. wrapper_deferred = delay_cancellation(deferred)
  321. # Cancel the new `Deferred`, twice.
  322. wrapper_deferred.cancel()
  323. wrapper_deferred.cancel()
  324. self.assertNoResult(wrapper_deferred)
  325. self.assertFalse(
  326. deferred.called, "Original `Deferred` was unexpectedly cancelled"
  327. )
  328. # Now make the original `Deferred` fail.
  329. # The `Failure` must be consumed, otherwise unwanted tracebacks will be printed
  330. # in logs.
  331. deferred.errback(ValueError("abc"))
  332. self.assertIsNone(deferred.result, "`Failure` was not consumed")
  333. # Now that the original `Deferred` has failed, we should get a `CancelledError`.
  334. self.failureResultOf(wrapper_deferred, CancelledError)
  335. def test_propagates_cancelled_error(self):
  336. """Test that a `CancelledError` from the original `Deferred` gets propagated."""
  337. deferred: "Deferred[str]" = Deferred()
  338. wrapper_deferred = delay_cancellation(deferred)
  339. # Fail the original `Deferred` with a `CancelledError`.
  340. cancelled_error = CancelledError()
  341. deferred.errback(cancelled_error)
  342. # The new `Deferred` should fail with exactly the same `CancelledError`.
  343. self.assertTrue(wrapper_deferred.called)
  344. self.assertIs(cancelled_error, self.failureResultOf(wrapper_deferred).value)
  345. def test_preserves_logcontext(self):
  346. """Test that logging contexts are preserved."""
  347. blocking_d: "Deferred[None]" = Deferred()
  348. async def inner():
  349. await make_deferred_yieldable(blocking_d)
  350. async def outer():
  351. with LoggingContext("c") as c:
  352. try:
  353. await delay_cancellation(defer.ensureDeferred(inner()))
  354. self.fail("`CancelledError` was not raised")
  355. except CancelledError:
  356. self.assertEqual(c, current_context())
  357. # Succeed with no error, unless the logging context is wrong.
  358. # Run and block inside `inner()`.
  359. d = defer.ensureDeferred(outer())
  360. self.assertEqual(SENTINEL_CONTEXT, current_context())
  361. d.cancel()
  362. # Now unblock. `outer()` will consume the `CancelledError` and check the
  363. # logging context.
  364. blocking_d.callback(None)
  365. self.successResultOf(d)