test_worker_lock.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # Copyright 2023 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 twisted.test.proto_helpers import MemoryReactor
  16. from synapse.server import HomeServer
  17. from synapse.util import Clock
  18. from tests import unittest
  19. from tests.replication._base import BaseMultiWorkerStreamTestCase
  20. class WorkerLockTestCase(unittest.HomeserverTestCase):
  21. def prepare(
  22. self, reactor: MemoryReactor, clock: Clock, homeserver: HomeServer
  23. ) -> None:
  24. self.worker_lock_handler = self.hs.get_worker_locks_handler()
  25. def test_wait_for_lock_locally(self) -> None:
  26. """Test waiting for a lock on a single worker"""
  27. lock1 = self.worker_lock_handler.acquire_lock("name", "key")
  28. self.get_success(lock1.__aenter__())
  29. lock2 = self.worker_lock_handler.acquire_lock("name", "key")
  30. d2 = defer.ensureDeferred(lock2.__aenter__())
  31. self.assertNoResult(d2)
  32. self.get_success(lock1.__aexit__(None, None, None))
  33. self.get_success(d2)
  34. self.get_success(lock2.__aexit__(None, None, None))
  35. class WorkerLockWorkersTestCase(BaseMultiWorkerStreamTestCase):
  36. def prepare(
  37. self, reactor: MemoryReactor, clock: Clock, homeserver: HomeServer
  38. ) -> None:
  39. self.main_worker_lock_handler = self.hs.get_worker_locks_handler()
  40. def test_wait_for_lock_worker(self) -> None:
  41. """Test waiting for a lock on another worker"""
  42. worker = self.make_worker_hs(
  43. "synapse.app.generic_worker",
  44. extra_config={
  45. "redis": {"enabled": True},
  46. },
  47. )
  48. worker_lock_handler = worker.get_worker_locks_handler()
  49. lock1 = self.main_worker_lock_handler.acquire_lock("name", "key")
  50. self.get_success(lock1.__aenter__())
  51. lock2 = worker_lock_handler.acquire_lock("name", "key")
  52. d2 = defer.ensureDeferred(lock2.__aenter__())
  53. self.assertNoResult(d2)
  54. self.get_success(lock1.__aexit__(None, None, None))
  55. self.get_success(d2)
  56. self.get_success(lock2.__aexit__(None, None, None))