snapshot.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. # Copyright 2014-2016 OpenMarket Ltd
  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 typing import TYPE_CHECKING, List, Optional, Tuple
  15. import attr
  16. from frozendict import frozendict
  17. from synapse.appservice import ApplicationService
  18. from synapse.events import EventBase
  19. from synapse.types import JsonDict, StateMap
  20. if TYPE_CHECKING:
  21. from synapse.storage.controllers import StorageControllers
  22. from synapse.storage.databases.main import DataStore
  23. from synapse.storage.state import StateFilter
  24. @attr.s(slots=True, auto_attribs=True)
  25. class EventContext:
  26. """
  27. Holds information relevant to persisting an event
  28. Attributes:
  29. rejected: A rejection reason if the event was rejected, else None
  30. _state_group: The ID of the state group for this event. Note that state events
  31. are persisted with a state group which includes the new event, so this is
  32. effectively the state *after* the event in question.
  33. For a *rejected* state event, where the state of the rejected event is
  34. ignored, this state_group should never make it into the
  35. event_to_state_groups table. Indeed, inspecting this value for a rejected
  36. state event is almost certainly incorrect.
  37. For an outlier, where we don't have the state at the event, this will be
  38. None.
  39. Note that this is a private attribute: it should be accessed via
  40. the ``state_group`` property.
  41. state_group_before_event: The ID of the state group representing the state
  42. of the room before this event.
  43. If this is a non-state event, this will be the same as ``state_group``. If
  44. it's a state event, it will be the same as ``prev_group``.
  45. If ``state_group`` is None (ie, the event is an outlier),
  46. ``state_group_before_event`` will always also be ``None``.
  47. state_delta_due_to_event: If `state_group` and `state_group_before_event` are not None
  48. then this is the delta of the state between the two groups.
  49. prev_group: If it is known, ``state_group``'s prev_group. Note that this being
  50. None does not necessarily mean that ``state_group`` does not have
  51. a prev_group!
  52. If the event is a state event, this is normally the same as
  53. ``state_group_before_event``.
  54. If ``state_group`` is None (ie, the event is an outlier), ``prev_group``
  55. will always also be ``None``.
  56. Note that this *not* (necessarily) the state group associated with
  57. ``_prev_state_ids``.
  58. delta_ids: If ``prev_group`` is not None, the state delta between ``prev_group``
  59. and ``state_group``.
  60. app_service: If this event is being sent by a (local) application service, that
  61. app service.
  62. partial_state: if True, we may be storing this event with a temporary,
  63. incomplete state.
  64. """
  65. _storage: "StorageControllers"
  66. rejected: Optional[str] = None
  67. _state_group: Optional[int] = None
  68. state_group_before_event: Optional[int] = None
  69. _state_delta_due_to_event: Optional[StateMap[str]] = None
  70. prev_group: Optional[int] = None
  71. delta_ids: Optional[StateMap[str]] = None
  72. app_service: Optional[ApplicationService] = None
  73. partial_state: bool = False
  74. @staticmethod
  75. def with_state(
  76. storage: "StorageControllers",
  77. state_group: Optional[int],
  78. state_group_before_event: Optional[int],
  79. state_delta_due_to_event: Optional[StateMap[str]],
  80. partial_state: bool,
  81. prev_group: Optional[int] = None,
  82. delta_ids: Optional[StateMap[str]] = None,
  83. ) -> "EventContext":
  84. return EventContext(
  85. storage=storage,
  86. state_group=state_group,
  87. state_group_before_event=state_group_before_event,
  88. state_delta_due_to_event=state_delta_due_to_event,
  89. prev_group=prev_group,
  90. delta_ids=delta_ids,
  91. partial_state=partial_state,
  92. )
  93. @staticmethod
  94. def for_outlier(
  95. storage: "StorageControllers",
  96. ) -> "EventContext":
  97. """Return an EventContext instance suitable for persisting an outlier event"""
  98. return EventContext(storage=storage)
  99. async def serialize(self, event: EventBase, store: "DataStore") -> JsonDict:
  100. """Converts self to a type that can be serialized as JSON, and then
  101. deserialized by `deserialize`
  102. Args:
  103. event: The event that this context relates to
  104. Returns:
  105. The serialized event.
  106. """
  107. return {
  108. "state_group": self._state_group,
  109. "state_group_before_event": self.state_group_before_event,
  110. "rejected": self.rejected,
  111. "prev_group": self.prev_group,
  112. "state_delta_due_to_event": _encode_state_dict(
  113. self._state_delta_due_to_event
  114. ),
  115. "delta_ids": _encode_state_dict(self.delta_ids),
  116. "app_service_id": self.app_service.id if self.app_service else None,
  117. "partial_state": self.partial_state,
  118. }
  119. @staticmethod
  120. def deserialize(storage: "StorageControllers", input: JsonDict) -> "EventContext":
  121. """Converts a dict that was produced by `serialize` back into a
  122. EventContext.
  123. Args:
  124. storage: Used to convert AS ID to AS object and fetch state.
  125. input: A dict produced by `serialize`
  126. Returns:
  127. The event context.
  128. """
  129. context = EventContext(
  130. # We use the state_group and prev_state_id stuff to pull the
  131. # current_state_ids out of the DB and construct prev_state_ids.
  132. storage=storage,
  133. state_group=input["state_group"],
  134. state_group_before_event=input["state_group_before_event"],
  135. prev_group=input["prev_group"],
  136. state_delta_due_to_event=_decode_state_dict(
  137. input["state_delta_due_to_event"]
  138. ),
  139. delta_ids=_decode_state_dict(input["delta_ids"]),
  140. rejected=input["rejected"],
  141. partial_state=input.get("partial_state", False),
  142. )
  143. app_service_id = input["app_service_id"]
  144. if app_service_id:
  145. context.app_service = storage.main.get_app_service_by_id(app_service_id)
  146. return context
  147. @property
  148. def state_group(self) -> Optional[int]:
  149. """The ID of the state group for this event.
  150. Note that state events are persisted with a state group which includes the new
  151. event, so this is effectively the state *after* the event in question.
  152. For an outlier, where we don't have the state at the event, this will be None.
  153. It is an error to access this for a rejected event, since rejected state should
  154. not make it into the room state. Accessing this property will raise an exception
  155. if ``rejected`` is set.
  156. """
  157. if self.rejected:
  158. raise RuntimeError("Attempt to access state_group of rejected event")
  159. return self._state_group
  160. async def get_current_state_ids(
  161. self, state_filter: Optional["StateFilter"] = None
  162. ) -> Optional[StateMap[str]]:
  163. """
  164. Gets the room state map, including this event - ie, the state in ``state_group``
  165. It is an error to access this for a rejected event, since rejected state should
  166. not make it into the room state. This method will raise an exception if
  167. ``rejected`` is set.
  168. Arg:
  169. state_filter: specifies the type of state event to fetch from DB, example: EventTypes.JoinRules
  170. Returns:
  171. Returns None if state_group is None, which happens when the associated
  172. event is an outlier.
  173. Maps a (type, state_key) to the event ID of the state event matching
  174. this tuple.
  175. """
  176. if self.rejected:
  177. raise RuntimeError("Attempt to access state_ids of rejected event")
  178. assert self._state_delta_due_to_event is not None
  179. prev_state_ids = await self.get_prev_state_ids(state_filter)
  180. if self._state_delta_due_to_event:
  181. prev_state_ids = dict(prev_state_ids)
  182. prev_state_ids.update(self._state_delta_due_to_event)
  183. return prev_state_ids
  184. async def get_prev_state_ids(
  185. self, state_filter: Optional["StateFilter"] = None
  186. ) -> StateMap[str]:
  187. """
  188. Gets the room state map, excluding this event.
  189. For a non-state event, this will be the same as get_current_state_ids().
  190. Args:
  191. state_filter: specifies the type of state event to fetch from DB, example: EventTypes.JoinRules
  192. Returns:
  193. Returns {} if state_group is None, which happens when the associated
  194. event is an outlier.
  195. Maps a (type, state_key) to the event ID of the state event matching
  196. this tuple.
  197. """
  198. assert self.state_group_before_event is not None
  199. return await self._storage.state.get_state_ids_for_group(
  200. self.state_group_before_event, state_filter
  201. )
  202. def _encode_state_dict(
  203. state_dict: Optional[StateMap[str]],
  204. ) -> Optional[List[Tuple[str, str, str]]]:
  205. """Since dicts of (type, state_key) -> event_id cannot be serialized in
  206. JSON we need to convert them to a form that can.
  207. """
  208. if state_dict is None:
  209. return None
  210. return [(etype, state_key, v) for (etype, state_key), v in state_dict.items()]
  211. def _decode_state_dict(
  212. input: Optional[List[Tuple[str, str, str]]]
  213. ) -> Optional[StateMap[str]]:
  214. """Decodes a state dict encoded using `_encode_state_dict` above"""
  215. if input is None:
  216. return None
  217. return frozendict({(etype, state_key): v for etype, state_key, v in input})