state.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2022 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from typing import (
  17. TYPE_CHECKING,
  18. Callable,
  19. Collection,
  20. Dict,
  21. Iterable,
  22. List,
  23. Mapping,
  24. Optional,
  25. Set,
  26. Tuple,
  27. TypeVar,
  28. )
  29. import attr
  30. from frozendict import frozendict
  31. from synapse.api.constants import EventTypes
  32. from synapse.types import MutableStateMap, StateKey, StateMap
  33. if TYPE_CHECKING:
  34. from typing import FrozenSet # noqa: used within quoted type hint; flake8 sad
  35. logger = logging.getLogger(__name__)
  36. # Used for generic functions below
  37. T = TypeVar("T")
  38. @attr.s(slots=True, frozen=True, auto_attribs=True)
  39. class StateFilter:
  40. """A filter used when querying for state.
  41. Attributes:
  42. types: Map from type to set of state keys (or None). This specifies
  43. which state_keys for the given type to fetch from the DB. If None
  44. then all events with that type are fetched. If the set is empty
  45. then no events with that type are fetched.
  46. include_others: Whether to fetch events with types that do not
  47. appear in `types`.
  48. """
  49. types: "frozendict[str, Optional[FrozenSet[str]]]"
  50. include_others: bool = False
  51. def __attrs_post_init__(self) -> None:
  52. # If `include_others` is set we canonicalise the filter by removing
  53. # wildcards from the types dictionary
  54. if self.include_others:
  55. # this is needed to work around the fact that StateFilter is frozen
  56. object.__setattr__(
  57. self,
  58. "types",
  59. frozendict({k: v for k, v in self.types.items() if v is not None}),
  60. )
  61. @staticmethod
  62. def all() -> "StateFilter":
  63. """Returns a filter that fetches everything.
  64. Returns:
  65. The state filter.
  66. """
  67. return _ALL_STATE_FILTER
  68. @staticmethod
  69. def none() -> "StateFilter":
  70. """Returns a filter that fetches nothing.
  71. Returns:
  72. The new state filter.
  73. """
  74. return _NONE_STATE_FILTER
  75. @staticmethod
  76. def from_types(types: Iterable[Tuple[str, Optional[str]]]) -> "StateFilter":
  77. """Creates a filter that only fetches the given types
  78. Args:
  79. types: A list of type and state keys to fetch. A state_key of None
  80. fetches everything for that type
  81. Returns:
  82. The new state filter.
  83. """
  84. type_dict: Dict[str, Optional[Set[str]]] = {}
  85. for typ, s in types:
  86. if typ in type_dict:
  87. if type_dict[typ] is None:
  88. continue
  89. if s is None:
  90. type_dict[typ] = None
  91. continue
  92. type_dict.setdefault(typ, set()).add(s) # type: ignore
  93. return StateFilter(
  94. types=frozendict(
  95. (k, frozenset(v) if v is not None else None)
  96. for k, v in type_dict.items()
  97. )
  98. )
  99. @staticmethod
  100. def from_lazy_load_member_list(members: Iterable[str]) -> "StateFilter":
  101. """Creates a filter that returns all non-member events, plus the member
  102. events for the given users
  103. Args:
  104. members: Set of user IDs
  105. Returns:
  106. The new state filter
  107. """
  108. return StateFilter(
  109. types=frozendict({EventTypes.Member: frozenset(members)}),
  110. include_others=True,
  111. )
  112. @staticmethod
  113. def freeze(
  114. types: Mapping[str, Optional[Collection[str]]], include_others: bool
  115. ) -> "StateFilter":
  116. """
  117. Returns a (frozen) StateFilter with the same contents as the parameters
  118. specified here, which can be made of mutable types.
  119. """
  120. types_with_frozen_values: Dict[str, Optional[FrozenSet[str]]] = {}
  121. for state_types, state_keys in types.items():
  122. if state_keys is not None:
  123. types_with_frozen_values[state_types] = frozenset(state_keys)
  124. else:
  125. types_with_frozen_values[state_types] = None
  126. return StateFilter(
  127. frozendict(types_with_frozen_values), include_others=include_others
  128. )
  129. def return_expanded(self) -> "StateFilter":
  130. """Creates a new StateFilter where type wild cards have been removed
  131. (except for memberships). The returned filter is a superset of the
  132. current one, i.e. anything that passes the current filter will pass
  133. the returned filter.
  134. This helps the caching as the DictionaryCache knows if it has *all* the
  135. state, but does not know if it has all of the keys of a particular type,
  136. which makes wildcard lookups expensive unless we have a complete cache.
  137. Hence, if we are doing a wildcard lookup, populate the cache fully so
  138. that we can do an efficient lookup next time.
  139. Note that since we have two caches, one for membership events and one for
  140. other events, we can be a bit more clever than simply returning
  141. `StateFilter.all()` if `has_wildcards()` is True.
  142. We return a StateFilter where:
  143. 1. the list of membership events to return is the same
  144. 2. if there is a wildcard that matches non-member events we
  145. return all non-member events
  146. Returns:
  147. The new state filter.
  148. """
  149. if self.is_full():
  150. # If we're going to return everything then there's nothing to do
  151. return self
  152. if not self.has_wildcards():
  153. # If there are no wild cards, there's nothing to do
  154. return self
  155. if EventTypes.Member in self.types:
  156. get_all_members = self.types[EventTypes.Member] is None
  157. else:
  158. get_all_members = self.include_others
  159. has_non_member_wildcard = self.include_others or any(
  160. state_keys is None
  161. for t, state_keys in self.types.items()
  162. if t != EventTypes.Member
  163. )
  164. if not has_non_member_wildcard:
  165. # If there are no non-member wild cards we can just return ourselves
  166. return self
  167. if get_all_members:
  168. # We want to return everything.
  169. return StateFilter.all()
  170. elif EventTypes.Member in self.types:
  171. # We want to return all non-members, but only particular
  172. # memberships
  173. return StateFilter(
  174. types=frozendict({EventTypes.Member: self.types[EventTypes.Member]}),
  175. include_others=True,
  176. )
  177. else:
  178. # We want to return all non-members
  179. return _ALL_NON_MEMBER_STATE_FILTER
  180. def make_sql_filter_clause(self) -> Tuple[str, List[str]]:
  181. """Converts the filter to an SQL clause.
  182. For example:
  183. f = StateFilter.from_types([("m.room.create", "")])
  184. clause, args = f.make_sql_filter_clause()
  185. clause == "(type = ? AND state_key = ?)"
  186. args == ['m.room.create', '']
  187. Returns:
  188. The SQL string (may be empty) and arguments. An empty SQL string is
  189. returned when the filter matches everything (i.e. is "full").
  190. """
  191. where_clause = ""
  192. where_args: List[str] = []
  193. if self.is_full():
  194. return where_clause, where_args
  195. if not self.include_others and not self.types:
  196. # i.e. this is an empty filter, so we need to return a clause that
  197. # will match nothing
  198. return "1 = 2", []
  199. # First we build up a lost of clauses for each type/state_key combo
  200. clauses = []
  201. for etype, state_keys in self.types.items():
  202. if state_keys is None:
  203. clauses.append("(type = ?)")
  204. where_args.append(etype)
  205. continue
  206. for state_key in state_keys:
  207. clauses.append("(type = ? AND state_key = ?)")
  208. where_args.extend((etype, state_key))
  209. # This will match anything that appears in `self.types`
  210. where_clause = " OR ".join(clauses)
  211. # If we want to include stuff that's not in the types dict then we add
  212. # a `OR type NOT IN (...)` clause to the end.
  213. if self.include_others:
  214. if where_clause:
  215. where_clause += " OR "
  216. where_clause += "type NOT IN (%s)" % (",".join(["?"] * len(self.types)),)
  217. where_args.extend(self.types)
  218. return where_clause, where_args
  219. def max_entries_returned(self) -> Optional[int]:
  220. """Returns the maximum number of entries this filter will return if
  221. known, otherwise returns None.
  222. For example a simple state filter asking for `("m.room.create", "")`
  223. will return 1, whereas the default state filter will return None.
  224. This is used to bail out early if the right number of entries have been
  225. fetched.
  226. """
  227. if self.has_wildcards():
  228. return None
  229. return len(self.concrete_types())
  230. def filter_state(self, state_dict: StateMap[T]) -> MutableStateMap[T]:
  231. """Returns the state filtered with by this StateFilter.
  232. Args:
  233. state: The state map to filter
  234. Returns:
  235. The filtered state map.
  236. This is a copy, so it's safe to mutate.
  237. """
  238. if self.is_full():
  239. return dict(state_dict)
  240. filtered_state = {}
  241. for k, v in state_dict.items():
  242. typ, state_key = k
  243. if typ in self.types:
  244. state_keys = self.types[typ]
  245. if state_keys is None or state_key in state_keys:
  246. filtered_state[k] = v
  247. elif self.include_others:
  248. filtered_state[k] = v
  249. return filtered_state
  250. def is_full(self) -> bool:
  251. """Whether this filter fetches everything or not
  252. Returns:
  253. True if the filter fetches everything.
  254. """
  255. return self.include_others and not self.types
  256. def has_wildcards(self) -> bool:
  257. """Whether the filter includes wildcards or is attempting to fetch
  258. specific state.
  259. Returns:
  260. True if the filter includes wildcards.
  261. """
  262. return self.include_others or any(
  263. state_keys is None for state_keys in self.types.values()
  264. )
  265. def concrete_types(self) -> List[Tuple[str, str]]:
  266. """Returns a list of concrete type/state_keys (i.e. not None) that
  267. will be fetched. This will be a complete list if `has_wildcards`
  268. returns False, but otherwise will be a subset (or even empty).
  269. Returns:
  270. A list of type/state_keys tuples.
  271. """
  272. return [
  273. (t, s)
  274. for t, state_keys in self.types.items()
  275. if state_keys is not None
  276. for s in state_keys
  277. ]
  278. def get_member_split(self) -> Tuple["StateFilter", "StateFilter"]:
  279. """Return the filter split into two: one which assumes it's exclusively
  280. matching against member state, and one which assumes it's matching
  281. against non member state.
  282. This is useful due to the returned filters giving correct results for
  283. `is_full()`, `has_wildcards()`, etc, when operating against maps that
  284. either exclusively contain member events or only contain non-member
  285. events. (Which is the case when dealing with the member vs non-member
  286. state caches).
  287. Returns:
  288. The member and non member filters
  289. """
  290. if EventTypes.Member in self.types:
  291. state_keys = self.types[EventTypes.Member]
  292. if state_keys is None:
  293. member_filter = StateFilter.all()
  294. else:
  295. member_filter = StateFilter(frozendict({EventTypes.Member: state_keys}))
  296. elif self.include_others:
  297. member_filter = StateFilter.all()
  298. else:
  299. member_filter = StateFilter.none()
  300. non_member_filter = StateFilter(
  301. types=frozendict(
  302. {k: v for k, v in self.types.items() if k != EventTypes.Member}
  303. ),
  304. include_others=self.include_others,
  305. )
  306. return member_filter, non_member_filter
  307. def _decompose_into_four_parts(
  308. self,
  309. ) -> Tuple[Tuple[bool, Set[str]], Tuple[Set[str], Set[StateKey]]]:
  310. """
  311. Decomposes this state filter into 4 constituent parts, which can be
  312. thought of as this:
  313. all? - minus_wildcards + plus_wildcards + plus_state_keys
  314. where
  315. * all represents ALL state
  316. * minus_wildcards represents entire state types to remove
  317. * plus_wildcards represents entire state types to add
  318. * plus_state_keys represents individual state keys to add
  319. See `recompose_from_four_parts` for the other direction of this
  320. correspondence.
  321. """
  322. is_all = self.include_others
  323. excluded_types: Set[str] = {t for t in self.types if is_all}
  324. wildcard_types: Set[str] = {t for t, s in self.types.items() if s is None}
  325. concrete_keys: Set[StateKey] = set(self.concrete_types())
  326. return (is_all, excluded_types), (wildcard_types, concrete_keys)
  327. @staticmethod
  328. def _recompose_from_four_parts(
  329. all_part: bool,
  330. minus_wildcards: Set[str],
  331. plus_wildcards: Set[str],
  332. plus_state_keys: Set[StateKey],
  333. ) -> "StateFilter":
  334. """
  335. Recomposes a state filter from 4 parts.
  336. See `decompose_into_four_parts` (the other direction of this
  337. correspondence) for descriptions on each of the parts.
  338. """
  339. # {state type -> set of state keys OR None for wildcard}
  340. # (The same structure as that of a StateFilter.)
  341. new_types: Dict[str, Optional[Set[str]]] = {}
  342. # if we start with all, insert the excluded statetypes as empty sets
  343. # to prevent them from being included
  344. if all_part:
  345. new_types.update({state_type: set() for state_type in minus_wildcards})
  346. # insert the plus wildcards
  347. new_types.update({state_type: None for state_type in plus_wildcards})
  348. # insert the specific state keys
  349. for state_type, state_key in plus_state_keys:
  350. if state_type in new_types:
  351. entry = new_types[state_type]
  352. if entry is not None:
  353. entry.add(state_key)
  354. elif not all_part:
  355. # don't insert if the entire type is already included by
  356. # include_others as this would actually shrink the state allowed
  357. # by this filter.
  358. new_types[state_type] = {state_key}
  359. return StateFilter.freeze(new_types, include_others=all_part)
  360. def approx_difference(self, other: "StateFilter") -> "StateFilter":
  361. """
  362. Returns a state filter which represents `self - other`.
  363. This is useful for determining what state remains to be pulled out of the
  364. database if we want the state included by `self` but already have the state
  365. included by `other`.
  366. The returned state filter
  367. - MUST include all state events that are included by this filter (`self`)
  368. unless they are included by `other`;
  369. - MUST NOT include state events not included by this filter (`self`); and
  370. - MAY be an over-approximation: the returned state filter
  371. MAY additionally include some state events from `other`.
  372. This implementation attempts to return the narrowest such state filter.
  373. In the case that `self` contains wildcards for state types where
  374. `other` contains specific state keys, an approximation must be made:
  375. the returned state filter keeps the wildcard, as state filters are not
  376. able to express 'all state keys except some given examples'.
  377. e.g.
  378. StateFilter(m.room.member -> None (wildcard))
  379. minus
  380. StateFilter(m.room.member -> {'@wombat:example.org'})
  381. is approximated as
  382. StateFilter(m.room.member -> None (wildcard))
  383. """
  384. # We first transform self and other into an alternative representation:
  385. # - whether or not they include all events to begin with ('all')
  386. # - if so, which event types are excluded? ('excludes')
  387. # - which entire event types to include ('wildcards')
  388. # - which concrete state keys to include ('concrete state keys')
  389. (self_all, self_excludes), (
  390. self_wildcards,
  391. self_concrete_keys,
  392. ) = self._decompose_into_four_parts()
  393. (other_all, other_excludes), (
  394. other_wildcards,
  395. other_concrete_keys,
  396. ) = other._decompose_into_four_parts()
  397. # Start with an estimate of the difference based on self
  398. new_all = self_all
  399. # Wildcards from the other can be added to the exclusion filter
  400. new_excludes = self_excludes | other_wildcards
  401. # We remove wildcards that appeared as wildcards in the other
  402. new_wildcards = self_wildcards - other_wildcards
  403. # We filter out the concrete state keys that appear in the other
  404. # as wildcards or concrete state keys.
  405. new_concrete_keys = {
  406. (state_type, state_key)
  407. for (state_type, state_key) in self_concrete_keys
  408. if state_type not in other_wildcards
  409. } - other_concrete_keys
  410. if other_all:
  411. if self_all:
  412. # If self starts with all, then we add as wildcards any
  413. # types which appear in the other's exclusion filter (but
  414. # aren't in the self exclusion filter). This is as the other
  415. # filter will return everything BUT the types in its exclusion, so
  416. # we need to add those excluded types that also match the self
  417. # filter as wildcard types in the new filter.
  418. new_wildcards |= other_excludes.difference(self_excludes)
  419. # If other is an `include_others` then the difference isn't.
  420. new_all = False
  421. # (We have no need for excludes when we don't start with all, as there
  422. # is nothing to exclude.)
  423. new_excludes = set()
  424. # We also filter out all state types that aren't in the exclusion
  425. # list of the other.
  426. new_wildcards &= other_excludes
  427. new_concrete_keys = {
  428. (state_type, state_key)
  429. for (state_type, state_key) in new_concrete_keys
  430. if state_type in other_excludes
  431. }
  432. # Transform our newly-constructed state filter from the alternative
  433. # representation back into the normal StateFilter representation.
  434. return StateFilter._recompose_from_four_parts(
  435. new_all, new_excludes, new_wildcards, new_concrete_keys
  436. )
  437. def must_await_full_state(self, is_mine_id: Callable[[str], bool]) -> bool:
  438. """Check if we need to wait for full state to complete to calculate this state
  439. If we have a state filter which is completely satisfied even with partial
  440. state, then we don't need to await_full_state before we can return it.
  441. Args:
  442. is_mine_id: a callable which confirms if a given state_key matches a mxid
  443. of a local user
  444. """
  445. # TODO(faster_joins): it's not entirely clear that this is safe. In particular,
  446. # there may be circumstances in which we return a piece of state that, once we
  447. # resync the state, we discover is invalid. For example: if it turns out that
  448. # the sender of a piece of state wasn't actually in the room, then clearly that
  449. # state shouldn't have been returned.
  450. # We should at least add some tests around this to see what happens.
  451. # https://github.com/matrix-org/synapse/issues/13006
  452. # if we haven't requested membership events, then it depends on the value of
  453. # 'include_others'
  454. if EventTypes.Member not in self.types:
  455. return self.include_others
  456. # if we're looking for *all* membership events, then we have to wait
  457. member_state_keys = self.types[EventTypes.Member]
  458. if member_state_keys is None:
  459. return True
  460. # otherwise, consider whose membership we are looking for. If it's entirely
  461. # local users, then we don't need to wait.
  462. for state_key in member_state_keys:
  463. if not is_mine_id(state_key):
  464. # remote user
  465. return True
  466. # local users only
  467. return False
  468. _ALL_STATE_FILTER = StateFilter(types=frozendict(), include_others=True)
  469. _ALL_NON_MEMBER_STATE_FILTER = StateFilter(
  470. types=frozendict({EventTypes.Member: frozenset()}), include_others=True
  471. )
  472. _NONE_STATE_FILTER = StateFilter(types=frozendict(), include_others=False)