test_module_cache_invalidation.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # Copyright 2022 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. import logging
  15. import synapse
  16. from synapse.module_api import cached
  17. from tests.replication._base import BaseMultiWorkerStreamTestCase
  18. logger = logging.getLogger(__name__)
  19. FIRST_VALUE = "one"
  20. SECOND_VALUE = "two"
  21. KEY = "mykey"
  22. class TestCache:
  23. current_value = FIRST_VALUE
  24. @cached()
  25. async def cached_function(self, user_id: str) -> str:
  26. return self.current_value
  27. class ModuleCacheInvalidationTestCase(BaseMultiWorkerStreamTestCase):
  28. servlets = [
  29. synapse.rest.admin.register_servlets,
  30. ]
  31. def test_module_cache_full_invalidation(self) -> None:
  32. main_cache = TestCache()
  33. self.hs.get_module_api().register_cached_function(main_cache.cached_function)
  34. worker_hs = self.make_worker_hs("synapse.app.generic_worker")
  35. worker_cache = TestCache()
  36. worker_hs.get_module_api().register_cached_function(
  37. worker_cache.cached_function
  38. )
  39. self.assertEqual(FIRST_VALUE, self.get_success(main_cache.cached_function(KEY)))
  40. self.assertEqual(
  41. FIRST_VALUE, self.get_success(worker_cache.cached_function(KEY))
  42. )
  43. main_cache.current_value = SECOND_VALUE
  44. worker_cache.current_value = SECOND_VALUE
  45. # No invalidation yet, should return the cached value on both the main process and the worker
  46. self.assertEqual(FIRST_VALUE, self.get_success(main_cache.cached_function(KEY)))
  47. self.assertEqual(
  48. FIRST_VALUE, self.get_success(worker_cache.cached_function(KEY))
  49. )
  50. # Full invalidation on the main process, should be replicated on the worker that
  51. # should returned the updated value too
  52. self.get_success(
  53. self.hs.get_module_api().invalidate_cache(
  54. main_cache.cached_function, (KEY,)
  55. )
  56. )
  57. self.assertEqual(
  58. SECOND_VALUE, self.get_success(main_cache.cached_function(KEY))
  59. )
  60. self.assertEqual(
  61. SECOND_VALUE, self.get_success(worker_cache.cached_function(KEY))
  62. )