mirror of
https://github.com/element-hq/synapse.git
synced 2026-11-05 15:27:36 +00:00
The first Rust database function to get a cache, and the first Python `@cached` function to be replaced by one. The Rust `/versions` handler calls `Store::is_feature_enabled_for_user` on every authenticated request, and until now each call ran a query. The Python `is_feature_enabled` had a cache of the same rows under another name, which every writer would have had to invalidate alongside. Now there is one cache, keyed on `(user_id, feature)`, and both sides read through it. The main datastore builds the Rust `Store` in its `__init__`, over its own `db_pool`, and `hs.get_rust_store()` hands it to the Rust handlers: the datastore owns the store, the handlers borrow it. The store's `is_feature_enabled_for_user` reaches Python as a callable cache object, bound on the datastore under that name. Calling it answers a hit with an already-fired Deferred, without leaving the reactor thread, and only a miss goes through tokio. Being a `RustCache`, it is also what `_invalidate_cache_and_stream`, replication and `register_cache` take, so `set_features_for_user` invalidates it with the one call it already made, and the name is spelled once in Rust, where the cache is built. `is_feature_enabled` keeps its global-config short cut in Python and delegates the per-user lookup. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ULdieJyQoHNzeHq42H2M1p
221 lines
8.0 KiB
Python
221 lines
8.0 KiB
Python
#
|
|
# This file is licensed under the Affero General Public License (AGPL) version 3.
|
|
#
|
|
# Copyright 2023 The Matrix.org Foundation C.I.C.
|
|
# Copyright (C) 2023 New Vector, Ltd
|
|
#
|
|
# This program is free software: you can redistribute it and/or modify
|
|
# it under the terms of the GNU Affero General Public License as
|
|
# published by the Free Software Foundation, either version 3 of the
|
|
# License, or (at your option) any later version.
|
|
#
|
|
# See the GNU Affero General Public License for more details:
|
|
# <https://www.gnu.org/licenses/agpl-3.0.html>.
|
|
#
|
|
# Originally licensed under the Apache License, Version 2.0:
|
|
# <http://www.apache.org/licenses/LICENSE-2.0>.
|
|
#
|
|
# [This file includes modifications made by New Vector Limited]
|
|
#
|
|
#
|
|
from unittest.mock import Mock, call
|
|
|
|
from signedjson.key import generate_signing_key, get_verify_key
|
|
|
|
from synapse.rest.admin.experimental_features import ExperimentalFeature
|
|
from synapse.storage.database import LoggingTransaction
|
|
from synapse.storage.keys import FetchKeyResult
|
|
|
|
from tests.replication._base import BaseMultiWorkerStreamTestCase
|
|
from tests.unittest import HomeserverTestCase
|
|
|
|
|
|
class CacheInvalidationTestCase(HomeserverTestCase):
|
|
def setUp(self) -> None:
|
|
super().setUp()
|
|
self.store = self.hs.get_datastores().main
|
|
|
|
def test_bulk_invalidation(self) -> None:
|
|
master_invalidate = Mock()
|
|
|
|
self.store._get_cached_user_device.invalidate = master_invalidate
|
|
|
|
keys_to_invalidate = [
|
|
("a", "b"),
|
|
("c", "d"),
|
|
("e", "f"),
|
|
("g", "h"),
|
|
]
|
|
|
|
def test_txn(txn: LoggingTransaction) -> None:
|
|
self.store._invalidate_cache_and_stream_bulk(
|
|
txn,
|
|
# This is an arbitrarily chosen cached store function. It was chosen
|
|
# because it takes more than one argument. We'll use this later to
|
|
# check that the invalidation was actioned over replication.
|
|
cache_func=self.store._get_cached_user_device,
|
|
key_tuples=keys_to_invalidate,
|
|
)
|
|
|
|
self.get_success(
|
|
self.store.db_pool.runInteraction(
|
|
"test_invalidate_cache_and_stream_bulk", test_txn
|
|
)
|
|
)
|
|
|
|
master_invalidate.assert_has_calls(
|
|
[call(key_list) for key_list in keys_to_invalidate],
|
|
any_order=True,
|
|
)
|
|
|
|
|
|
class CacheInvalidationOverReplicationTestCase(BaseMultiWorkerStreamTestCase):
|
|
def setUp(self) -> None:
|
|
super().setUp()
|
|
self.store = self.hs.get_datastores().main
|
|
|
|
def test_bulk_invalidation_replicates(self) -> None:
|
|
"""Like test_bulk_invalidation, but also checks the invalidations replicate."""
|
|
master_invalidate = Mock()
|
|
worker_invalidate = Mock()
|
|
|
|
self.store._get_cached_user_device.invalidate = master_invalidate
|
|
worker = self.make_worker_hs("synapse.app.generic_worker")
|
|
worker_ds = worker.get_datastores().main
|
|
worker_ds._get_cached_user_device.invalidate = worker_invalidate
|
|
|
|
keys_to_invalidate = [
|
|
("a", "b"),
|
|
("c", "d"),
|
|
("e", "f"),
|
|
("g", "h"),
|
|
]
|
|
|
|
def test_txn(txn: LoggingTransaction) -> None:
|
|
self.store._invalidate_cache_and_stream_bulk(
|
|
txn,
|
|
# This is an arbitrarily chosen cached store function. It was chosen
|
|
# because it takes more than one argument. We'll use this later to
|
|
# check that the invalidation was actioned over replication.
|
|
cache_func=self.store._get_cached_user_device,
|
|
key_tuples=keys_to_invalidate,
|
|
)
|
|
|
|
assert self.store._cache_id_gen is not None
|
|
initial_token = self.store._cache_id_gen.get_current_token()
|
|
self.get_success(
|
|
self.database_pool.runInteraction(
|
|
"test_invalidate_cache_and_stream_bulk", test_txn
|
|
)
|
|
)
|
|
second_token = self.store._cache_id_gen.get_current_token()
|
|
|
|
self.assertGreaterEqual(second_token, initial_token + len(keys_to_invalidate))
|
|
|
|
self.get_success(
|
|
worker.get_replication_data_handler().wait_for_stream_position(
|
|
"master", "caches", second_token
|
|
)
|
|
)
|
|
|
|
master_invalidate.assert_has_calls(
|
|
[call(key_list) for key_list in keys_to_invalidate],
|
|
any_order=True,
|
|
)
|
|
worker_invalidate.assert_has_calls(
|
|
[call(key_list) for key_list in keys_to_invalidate],
|
|
any_order=True,
|
|
)
|
|
|
|
def test_server_keys_json_invalidation_replicates(self) -> None:
|
|
"""`_get_server_keys_json` takes a single argument which is itself a
|
|
tuple, and we can't send nested keys over replication: the keys are
|
|
JSON-encoded on the sending side and decoded again in
|
|
`process_replication_rows`. Check the round trip invalidates the right
|
|
cache entry on the worker.
|
|
"""
|
|
master_invalidate = Mock()
|
|
worker_invalidate = Mock()
|
|
|
|
self.store._get_server_keys_json.invalidate = master_invalidate
|
|
worker = self.make_worker_hs("synapse.app.generic_worker")
|
|
worker_ds = worker.get_datastores().main
|
|
worker_ds._get_server_keys_json.invalidate = worker_invalidate
|
|
|
|
signing_key = generate_signing_key("ver1")
|
|
verify_key = get_verify_key(signing_key)
|
|
key_id = f"{verify_key.alg}:{verify_key.version}"
|
|
|
|
assert self.store._cache_id_gen is not None
|
|
initial_token = self.store._cache_id_gen.get_current_token()
|
|
|
|
self.get_success(
|
|
self.store.store_server_keys_response(
|
|
"server1",
|
|
from_server="server2",
|
|
ts_added_ms=self.clock.time_msec(),
|
|
verify_keys={
|
|
key_id: FetchKeyResult(
|
|
verify_key=verify_key, valid_until_ts=200_000
|
|
),
|
|
},
|
|
response_json={},
|
|
)
|
|
)
|
|
second_token = self.store._cache_id_gen.get_current_token()
|
|
self.assertGreater(second_token, initial_token)
|
|
|
|
self.get_success(
|
|
worker.get_replication_data_handler().wait_for_stream_position(
|
|
"master", "caches", second_token
|
|
)
|
|
)
|
|
|
|
expected_key = (("server1", key_id),)
|
|
master_invalidate.assert_called_once_with(expected_key)
|
|
worker_invalidate.assert_called_once_with(expected_key)
|
|
|
|
def test_rust_cache_invalidation_replicates(self) -> None:
|
|
"""A write on one worker empties the Rust cache on another.
|
|
|
|
The Rust cache is bound on the datastore under its name, like a
|
|
`@cached` function, so a row on the caches stream naming it reaches it
|
|
through `getattr(store, name).invalidate(keys)`. The keys it sees are
|
|
strings, because the stream's column is `keys text[]`.
|
|
"""
|
|
worker = self.make_worker_hs("synapse.app.generic_worker")
|
|
worker_store = worker.get_datastores().main
|
|
|
|
user_id = self.get_success(
|
|
self.hs.get_registration_handler().register_user(localpart="user")
|
|
)
|
|
|
|
# Read through the worker's cache, so that it holds this user.
|
|
self.assertFalse(
|
|
self.get_success(
|
|
worker_store.is_feature_enabled_for_user(user_id, "msc3881")
|
|
)
|
|
)
|
|
self.assertEqual(len(worker_store.is_feature_enabled_for_user), 1)
|
|
|
|
assert self.store._cache_id_gen is not None
|
|
self.get_success(
|
|
self.store.set_features_for_user(
|
|
user_id, {ExperimentalFeature.MSC3881: True}
|
|
)
|
|
)
|
|
token = self.store._cache_id_gen.get_current_token()
|
|
|
|
self.get_success(
|
|
worker.get_replication_data_handler().wait_for_stream_position(
|
|
"master", "caches", token
|
|
)
|
|
)
|
|
|
|
self.assertEqual(len(worker_store.is_feature_enabled_for_user), 0)
|
|
self.assertTrue(
|
|
self.get_success(
|
|
worker_store.is_feature_enabled_for_user(user_id, "msc3881")
|
|
)
|
|
)
|