2016-01-28 11:37:41 -05:00
|
|
|
#
|
2023-11-21 15:29:58 -05:00
|
|
|
# This file is licensed under the Affero General Public License (AGPL) version 3.
|
|
|
|
#
|
2024-01-23 06:26:48 -05:00
|
|
|
# Copyright 2016 OpenMarket Ltd
|
2023-11-21 15:29:58 -05:00
|
|
|
# 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]
|
2016-01-28 11:37:41 -05:00
|
|
|
#
|
|
|
|
#
|
|
|
|
|
2018-07-09 02:09:20 -04:00
|
|
|
import logging
|
2020-05-11 13:45:23 -04:00
|
|
|
import math
|
2021-04-22 11:43:50 -04:00
|
|
|
from typing import Collection, Dict, FrozenSet, List, Mapping, Optional, Set, Union
|
2016-01-28 11:37:41 -05:00
|
|
|
|
2022-12-05 15:19:14 -05:00
|
|
|
import attr
|
2018-06-05 10:13:57 -04:00
|
|
|
from sortedcontainers import SortedDict
|
2016-01-28 11:37:41 -05:00
|
|
|
|
2018-07-09 02:09:20 -04:00
|
|
|
from synapse.util import caches
|
2016-01-28 11:37:41 -05:00
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2020-04-22 08:45:40 -04:00
|
|
|
# for now, assume all entities in the cache are strings
|
|
|
|
EntityType = str
|
2016-01-28 11:37:41 -05:00
|
|
|
|
2020-04-22 08:45:40 -04:00
|
|
|
|
2022-12-05 15:19:14 -05:00
|
|
|
@attr.s(auto_attribs=True, frozen=True, slots=True)
|
|
|
|
class AllEntitiesChangedResult:
|
|
|
|
"""Return type of `get_all_entities_changed`.
|
|
|
|
|
|
|
|
Callers must check that there was a cache hit, via `result.hit`, before
|
|
|
|
using the entities in `result.entities`.
|
|
|
|
|
|
|
|
This specifically does *not* implement helpers such as `__bool__` to ensure
|
|
|
|
that callers do the correct checks.
|
|
|
|
"""
|
|
|
|
|
|
|
|
_entities: Optional[List[EntityType]]
|
|
|
|
|
|
|
|
@property
|
|
|
|
def hit(self) -> bool:
|
|
|
|
return self._entities is not None
|
|
|
|
|
|
|
|
@property
|
|
|
|
def entities(self) -> List[EntityType]:
|
|
|
|
assert self._entities is not None
|
|
|
|
return self._entities
|
|
|
|
|
|
|
|
|
2020-04-22 08:45:40 -04:00
|
|
|
class StreamChangeCache:
|
2022-12-05 09:00:59 -05:00
|
|
|
"""
|
|
|
|
Keeps track of the stream positions of the latest change in a set of entities.
|
|
|
|
|
|
|
|
The entity will is typically a room ID or user ID, but can be any string.
|
2016-01-28 11:37:41 -05:00
|
|
|
|
2022-12-05 09:00:59 -05:00
|
|
|
Can be queried for whether a specific entity has changed after a stream position
|
|
|
|
or for a list of changed entities after a stream position. See the individual
|
|
|
|
methods for more information.
|
2016-01-28 11:37:41 -05:00
|
|
|
|
2022-12-05 09:00:59 -05:00
|
|
|
Only tracks to a maximum cache size, any position earlier than the earliest
|
|
|
|
known stream position must be treated as unknown.
|
2016-01-28 11:37:41 -05:00
|
|
|
"""
|
2018-06-05 10:13:57 -04:00
|
|
|
|
2020-04-22 08:45:40 -04:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
name: str,
|
|
|
|
current_stream_pos: int,
|
2021-10-06 06:20:49 -04:00
|
|
|
max_size: int = 10000,
|
2020-04-22 08:45:40 -04:00
|
|
|
prefilled_cache: Optional[Mapping[EntityType, int]] = None,
|
2021-10-06 06:20:49 -04:00
|
|
|
) -> None:
|
|
|
|
self._original_max_size: int = max_size
|
2020-05-11 13:45:23 -04:00
|
|
|
self._max_size = math.floor(max_size)
|
2020-04-22 08:45:40 -04:00
|
|
|
|
2022-12-05 09:00:59 -05:00
|
|
|
# map from stream id to the set of entities which changed at that stream id.
|
2021-07-15 12:46:54 -04:00
|
|
|
self._cache: SortedDict[int, Set[EntityType]] = SortedDict()
|
2022-12-05 09:00:59 -05:00
|
|
|
# map from entity to the stream ID of the latest change for that entity.
|
|
|
|
#
|
|
|
|
# Must be kept in sync with _cache.
|
|
|
|
self._entity_to_key: Dict[EntityType, int] = {}
|
2020-04-22 08:45:40 -04:00
|
|
|
|
|
|
|
# the earliest stream_pos for which we can reliably answer
|
|
|
|
# get_all_entities_changed. In other words, one less than the earliest
|
|
|
|
# stream_pos for which we know _cache is valid.
|
|
|
|
#
|
2016-01-28 11:37:41 -05:00
|
|
|
self._earliest_known_stream_pos = current_stream_pos
|
2022-12-05 09:00:59 -05:00
|
|
|
|
2016-01-28 11:37:41 -05:00
|
|
|
self.name = name
|
2020-05-11 13:45:23 -04:00
|
|
|
self.metrics = caches.register_cache(
|
|
|
|
"cache", self.name, self._cache, resize_callback=self.set_cache_factor
|
|
|
|
)
|
2016-01-28 11:37:41 -05:00
|
|
|
|
2018-06-05 10:13:57 -04:00
|
|
|
if prefilled_cache:
|
|
|
|
for entity, stream_pos in prefilled_cache.items():
|
|
|
|
self.entity_has_changed(entity, stream_pos)
|
2016-01-29 09:37:59 -05:00
|
|
|
|
2020-05-11 13:45:23 -04:00
|
|
|
def set_cache_factor(self, factor: float) -> bool:
|
|
|
|
"""
|
|
|
|
Set the cache factor for this individual cache.
|
|
|
|
|
|
|
|
This will trigger a resize if it changes, which may require evicting
|
|
|
|
items from the cache.
|
|
|
|
|
|
|
|
Returns:
|
2022-11-10 15:33:34 -05:00
|
|
|
Whether the cache changed size or not.
|
2020-05-11 13:45:23 -04:00
|
|
|
"""
|
|
|
|
new_size = math.floor(self._original_max_size * factor)
|
|
|
|
if new_size != self._max_size:
|
2024-05-03 13:00:08 -04:00
|
|
|
self._max_size = new_size
|
2020-05-11 13:45:23 -04:00
|
|
|
self._evict()
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
2020-04-22 08:45:40 -04:00
|
|
|
def has_entity_changed(self, entity: EntityType, stream_pos: int) -> bool:
|
2022-12-05 09:00:59 -05:00
|
|
|
"""
|
|
|
|
Returns True if the entity may have been updated after stream_pos.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
entity: The entity to check for changes.
|
|
|
|
stream_pos: The stream position to check for changes after.
|
|
|
|
|
|
|
|
Return:
|
|
|
|
True if the entity may have been updated, this happens if:
|
|
|
|
* The given stream position is at or earlier than the earliest
|
|
|
|
known stream position.
|
|
|
|
* The given stream position is earlier than the latest change for
|
|
|
|
the entity.
|
|
|
|
|
|
|
|
False otherwise:
|
|
|
|
* The entity is unknown.
|
|
|
|
* The given stream position is at or later than the latest change
|
|
|
|
for the entity.
|
|
|
|
"""
|
2020-06-16 08:51:47 -04:00
|
|
|
assert isinstance(stream_pos, int)
|
2016-01-28 11:37:41 -05:00
|
|
|
|
2022-12-05 09:00:59 -05:00
|
|
|
# _cache is not valid at or before the earliest known stream position, so
|
|
|
|
# return that the entity has changed.
|
|
|
|
if stream_pos <= self._earliest_known_stream_pos:
|
2016-06-02 06:29:44 -04:00
|
|
|
self.metrics.inc_misses()
|
2016-01-28 11:37:41 -05:00
|
|
|
return True
|
|
|
|
|
2022-12-05 09:00:59 -05:00
|
|
|
# If the entity is unknown, it hasn't changed.
|
2016-01-28 11:37:41 -05:00
|
|
|
latest_entity_change_pos = self._entity_to_key.get(entity, None)
|
|
|
|
if latest_entity_change_pos is None:
|
2016-06-02 06:29:44 -04:00
|
|
|
self.metrics.inc_hits()
|
2016-01-29 11:24:34 -05:00
|
|
|
return False
|
2016-01-28 11:37:41 -05:00
|
|
|
|
2022-12-05 09:00:59 -05:00
|
|
|
# This is a known entity, return true if the stream position is earlier
|
|
|
|
# than the last change.
|
2016-01-28 11:37:41 -05:00
|
|
|
if stream_pos < latest_entity_change_pos:
|
2016-06-02 06:29:44 -04:00
|
|
|
self.metrics.inc_misses()
|
2016-01-28 11:37:41 -05:00
|
|
|
return True
|
|
|
|
|
2022-12-05 09:00:59 -05:00
|
|
|
# Otherwise, the stream position is after the latest change: return false.
|
2016-06-02 06:29:44 -04:00
|
|
|
self.metrics.inc_hits()
|
2016-01-28 11:37:41 -05:00
|
|
|
return False
|
|
|
|
|
2020-04-22 08:45:40 -04:00
|
|
|
def get_entities_changed(
|
2024-05-06 07:56:52 -04:00
|
|
|
self, entities: Collection[EntityType], stream_pos: int, _perf_factor: int = 1
|
2020-05-05 12:07:59 -04:00
|
|
|
) -> Union[Set[EntityType], FrozenSet[EntityType]]:
|
2018-06-05 10:13:57 -04:00
|
|
|
"""
|
2022-12-05 09:00:59 -05:00
|
|
|
Returns the subset of the given entities that have had changes after the given position.
|
|
|
|
|
|
|
|
Entities unknown to the cache will be returned.
|
|
|
|
|
|
|
|
If the position is too old it will just return the given list.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
entities: Entities to check for changes.
|
|
|
|
stream_pos: The stream position to check for changes after.
|
2024-05-06 07:56:52 -04:00
|
|
|
_perf_factor: Used by unit tests to choose when to use each
|
|
|
|
optimisation.
|
2022-12-05 09:00:59 -05:00
|
|
|
|
|
|
|
Return:
|
|
|
|
A subset of entities which have changed after the given stream position.
|
|
|
|
|
|
|
|
This will be all entities if the given stream position is at or earlier
|
|
|
|
than the earliest known stream position.
|
2016-01-28 11:37:41 -05:00
|
|
|
"""
|
2024-05-06 07:56:52 -04:00
|
|
|
if not self._cache or stream_pos <= self._earliest_known_stream_pos:
|
|
|
|
self.metrics.inc_misses()
|
|
|
|
return set(entities)
|
|
|
|
|
|
|
|
# If there have been tonnes of changes compared with the number of
|
|
|
|
# entities, it is faster to check each entities stream ordering
|
|
|
|
# one-by-one.
|
|
|
|
max_stream_pos, _ = self._cache.peekitem()
|
|
|
|
if max_stream_pos - stream_pos > _perf_factor * len(entities):
|
|
|
|
self.metrics.inc_hits()
|
|
|
|
return {
|
|
|
|
entity
|
|
|
|
for entity in entities
|
|
|
|
if self._entity_to_key.get(entity, -1) > stream_pos
|
|
|
|
}
|
|
|
|
|
2022-12-05 15:19:14 -05:00
|
|
|
cache_result = self.get_all_entities_changed(stream_pos)
|
|
|
|
if cache_result.hit:
|
2020-05-05 12:07:59 -04:00
|
|
|
# We now do an intersection, trying to do so in the most efficient
|
|
|
|
# way possible (some of these sets are *large*). First check in the
|
2022-12-05 09:00:59 -05:00
|
|
|
# given iterable is already a set that we can reuse, otherwise we
|
2020-05-05 12:07:59 -04:00
|
|
|
# create a set of the *smallest* of the two iterables and call
|
|
|
|
# `intersection(..)` on it (this can be twice as fast as the reverse).
|
|
|
|
if isinstance(entities, (set, frozenset)):
|
2022-12-05 15:19:14 -05:00
|
|
|
result = entities.intersection(cache_result.entities)
|
|
|
|
elif len(cache_result.entities) < len(entities):
|
|
|
|
result = set(cache_result.entities).intersection(entities)
|
2020-05-05 12:07:59 -04:00
|
|
|
else:
|
2022-12-05 15:19:14 -05:00
|
|
|
result = set(entities).intersection(cache_result.entities)
|
2016-06-02 06:29:44 -04:00
|
|
|
self.metrics.inc_hits()
|
2016-01-28 11:37:41 -05:00
|
|
|
else:
|
2018-06-05 10:13:57 -04:00
|
|
|
result = set(entities)
|
2016-06-02 06:29:44 -04:00
|
|
|
self.metrics.inc_misses()
|
2016-01-28 11:37:41 -05:00
|
|
|
|
|
|
|
return result
|
|
|
|
|
2020-04-22 08:45:40 -04:00
|
|
|
def has_any_entity_changed(self, stream_pos: int) -> bool:
|
2022-12-05 09:00:59 -05:00
|
|
|
"""
|
|
|
|
Returns true if any entity has changed after the given stream position.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
stream_pos: The stream position to check for changes after.
|
|
|
|
|
|
|
|
Return:
|
|
|
|
True if any entity has changed after the given stream position or
|
|
|
|
if the given stream position is at or earlier than the earliest
|
|
|
|
known stream position.
|
|
|
|
|
|
|
|
False otherwise.
|
|
|
|
"""
|
|
|
|
assert isinstance(stream_pos, int)
|
2017-05-31 10:46:36 -04:00
|
|
|
|
2022-12-05 09:00:59 -05:00
|
|
|
# _cache is not valid at or before the earliest known stream position, so
|
|
|
|
# return that an entity has changed.
|
|
|
|
if stream_pos <= self._earliest_known_stream_pos:
|
2017-05-31 10:46:36 -04:00
|
|
|
self.metrics.inc_misses()
|
|
|
|
return True
|
|
|
|
|
2022-12-08 11:35:49 -05:00
|
|
|
# If the cache is empty, nothing can have changed.
|
|
|
|
if not self._cache:
|
|
|
|
self.metrics.inc_misses()
|
|
|
|
return False
|
|
|
|
|
2022-12-05 09:00:59 -05:00
|
|
|
self.metrics.inc_hits()
|
|
|
|
return stream_pos < self._cache.peekitem()[0]
|
|
|
|
|
2022-12-05 15:19:14 -05:00
|
|
|
def get_all_entities_changed(self, stream_pos: int) -> AllEntitiesChangedResult:
|
2022-12-05 09:00:59 -05:00
|
|
|
"""
|
|
|
|
Returns all entities that have had changes after the given position.
|
|
|
|
|
2022-12-05 15:19:14 -05:00
|
|
|
If the stream change cache does not go far enough back, i.e. the
|
|
|
|
position is too old, it will return None.
|
2020-04-22 08:45:40 -04:00
|
|
|
|
|
|
|
Returns the entities in the order that they were changed.
|
2022-12-05 09:00:59 -05:00
|
|
|
|
|
|
|
Args:
|
|
|
|
stream_pos: The stream position to check for changes after.
|
|
|
|
|
|
|
|
Return:
|
2022-12-05 15:19:14 -05:00
|
|
|
A class indicating if we have the requested data cached, and if so
|
|
|
|
includes the entities in the order they were changed.
|
2016-02-23 09:48:23 -05:00
|
|
|
"""
|
2022-12-05 09:00:59 -05:00
|
|
|
assert isinstance(stream_pos, int)
|
2016-02-23 09:48:23 -05:00
|
|
|
|
2022-12-05 09:00:59 -05:00
|
|
|
# _cache is not valid at or before the earliest known stream position, so
|
|
|
|
# return None to mark that it is unknown if an entity has changed.
|
|
|
|
if stream_pos <= self._earliest_known_stream_pos:
|
2022-12-05 15:19:14 -05:00
|
|
|
return AllEntitiesChangedResult(None)
|
2016-02-23 09:48:23 -05:00
|
|
|
|
2021-07-15 12:46:54 -04:00
|
|
|
changed_entities: List[EntityType] = []
|
2020-04-22 08:45:40 -04:00
|
|
|
|
|
|
|
for k in self._cache.islice(start=self._cache.bisect_right(stream_pos)):
|
|
|
|
changed_entities.extend(self._cache[k])
|
2022-12-05 15:19:14 -05:00
|
|
|
return AllEntitiesChangedResult(changed_entities)
|
2020-04-22 08:45:40 -04:00
|
|
|
|
|
|
|
def entity_has_changed(self, entity: EntityType, stream_pos: int) -> None:
|
2016-01-28 11:37:41 -05:00
|
|
|
"""
|
2022-12-05 09:00:59 -05:00
|
|
|
Informs the cache that the entity has been changed at the given position.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
entity: The entity to mark as changed.
|
|
|
|
stream_pos: The stream position to update the entity to.
|
|
|
|
"""
|
|
|
|
assert isinstance(stream_pos, int)
|
2016-01-28 11:37:41 -05:00
|
|
|
|
2022-12-05 09:00:59 -05:00
|
|
|
# For a change before _cache is valid (e.g. at or before the earliest known
|
|
|
|
# stream position) there's nothing to do.
|
2020-04-22 08:45:40 -04:00
|
|
|
if stream_pos <= self._earliest_known_stream_pos:
|
|
|
|
return
|
|
|
|
|
|
|
|
old_pos = self._entity_to_key.get(entity, None)
|
|
|
|
if old_pos is not None:
|
|
|
|
if old_pos >= stream_pos:
|
|
|
|
# nothing to do
|
|
|
|
return
|
|
|
|
e = self._cache[old_pos]
|
|
|
|
e.remove(entity)
|
|
|
|
if not e:
|
|
|
|
# cache at this point is now empty
|
|
|
|
del self._cache[old_pos]
|
|
|
|
|
|
|
|
e1 = self._cache.get(stream_pos)
|
|
|
|
if e1 is None:
|
|
|
|
e1 = self._cache[stream_pos] = set()
|
|
|
|
e1.add(entity)
|
|
|
|
self._entity_to_key[entity] = stream_pos
|
2020-05-11 13:45:23 -04:00
|
|
|
self._evict()
|
2020-04-22 08:45:40 -04:00
|
|
|
|
2021-09-10 12:03:18 -04:00
|
|
|
def _evict(self) -> None:
|
2022-12-05 09:00:59 -05:00
|
|
|
"""
|
|
|
|
Ensure the cache has not exceeded the maximum size.
|
|
|
|
|
|
|
|
Evicts entries until it is at the maximum size.
|
|
|
|
"""
|
2022-11-10 15:33:34 -05:00
|
|
|
# if the cache is too big, remove entries
|
2020-05-11 13:45:23 -04:00
|
|
|
while len(self._cache) > self._max_size:
|
|
|
|
k, r = self._cache.popitem(0)
|
|
|
|
self._earliest_known_stream_pos = max(k, self._earliest_known_stream_pos)
|
|
|
|
for entity in r:
|
|
|
|
self._entity_to_key.pop(entity, None)
|
|
|
|
|
2020-04-22 08:45:40 -04:00
|
|
|
def get_max_pos_of_last_change(self, entity: EntityType) -> int:
|
2016-09-15 10:12:07 -04:00
|
|
|
"""Returns an upper bound of the stream id of the last change to an
|
|
|
|
entity.
|
2022-12-05 09:00:59 -05:00
|
|
|
|
|
|
|
Args:
|
|
|
|
entity: The entity to check.
|
|
|
|
|
|
|
|
Return:
|
|
|
|
The stream position of the latest change for the given entity or
|
|
|
|
the earliest known stream position if the entitiy is unknown.
|
2016-09-15 09:27:15 -04:00
|
|
|
"""
|
2016-09-15 10:12:07 -04:00
|
|
|
return self._entity_to_key.get(entity, self._earliest_known_stream_pos)
|