25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

547 satır
21 KiB

  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 abc import ABC, abstractmethod
  15. from typing import TYPE_CHECKING, Dict, List, Optional, Tuple
  16. import attr
  17. from immutabledict import immutabledict
  18. from synapse.appservice import ApplicationService
  19. from synapse.events import EventBase
  20. from synapse.logging.opentracing import tag_args, trace
  21. from synapse.types import JsonDict, StateMap
  22. if TYPE_CHECKING:
  23. from synapse.storage.controllers import StorageControllers
  24. from synapse.storage.databases import StateGroupDataStore
  25. from synapse.storage.databases.main import DataStore
  26. from synapse.types.state import StateFilter
  27. class UnpersistedEventContextBase(ABC):
  28. """
  29. This is a base class for EventContext and UnpersistedEventContext, objects which
  30. hold information relevant to storing an associated event. Note that an
  31. UnpersistedEventContexts must be converted into an EventContext before it is
  32. suitable to send to the db with its associated event.
  33. Attributes:
  34. _storage: storage controllers for interfacing with the database
  35. app_service: If the associated event is being sent by a (local) application service, that
  36. app service.
  37. """
  38. def __init__(self, storage_controller: "StorageControllers"):
  39. self._storage: "StorageControllers" = storage_controller
  40. self.app_service: Optional[ApplicationService] = None
  41. @abstractmethod
  42. async def persist(
  43. self,
  44. event: EventBase,
  45. ) -> "EventContext":
  46. """
  47. A method to convert an UnpersistedEventContext to an EventContext, suitable for
  48. sending to the database with the associated event.
  49. """
  50. @abstractmethod
  51. async def get_prev_state_ids(
  52. self, state_filter: Optional["StateFilter"] = None
  53. ) -> StateMap[str]:
  54. """
  55. Gets the room state at the event (ie not including the event if the event is a
  56. state event).
  57. Args:
  58. state_filter: specifies the type of state event to fetch from DB, example:
  59. EventTypes.JoinRules
  60. """
  61. @attr.s(slots=True, auto_attribs=True)
  62. class EventContext(UnpersistedEventContextBase):
  63. """
  64. Holds information relevant to persisting an event
  65. Attributes:
  66. rejected: A rejection reason if the event was rejected, else None
  67. _state_group: The ID of the state group for this event. Note that state events
  68. are persisted with a state group which includes the new event, so this is
  69. effectively the state *after* the event in question.
  70. For a *rejected* state event, where the state of the rejected event is
  71. ignored, this state_group should never make it into the
  72. event_to_state_groups table. Indeed, inspecting this value for a rejected
  73. state event is almost certainly incorrect.
  74. For an outlier, where we don't have the state at the event, this will be
  75. None.
  76. Note that this is a private attribute: it should be accessed via
  77. the ``state_group`` property.
  78. state_group_before_event: The ID of the state group representing the state
  79. of the room before this event.
  80. If this is a non-state event, this will be the same as ``state_group``. If
  81. it's a state event, it will be the same as ``prev_group``.
  82. If ``state_group`` is None (ie, the event is an outlier),
  83. ``state_group_before_event`` will always also be ``None``.
  84. state_delta_due_to_event: If `state_group` and `state_group_before_event` are not None
  85. then this is the delta of the state between the two groups.
  86. state_group_deltas: If not empty, this is a dict collecting a mapping of the state
  87. difference between state groups.
  88. The keys are a tuple of two integers: the initial group and final state group.
  89. The corresponding value is a state map representing the state delta between
  90. these state groups.
  91. The dictionary is expected to have at most two entries with state groups of:
  92. 1. The state group before the event and after the event.
  93. 2. The state group preceding the state group before the event and the
  94. state group before the event.
  95. This information is collected and stored as part of an optimization for persisting
  96. events.
  97. partial_state: if True, we may be storing this event with a temporary,
  98. incomplete state.
  99. """
  100. _storage: "StorageControllers"
  101. state_group_deltas: Dict[Tuple[int, int], StateMap[str]]
  102. rejected: Optional[str] = None
  103. _state_group: Optional[int] = None
  104. state_group_before_event: Optional[int] = None
  105. _state_delta_due_to_event: Optional[StateMap[str]] = None
  106. app_service: Optional[ApplicationService] = None
  107. partial_state: bool = False
  108. @staticmethod
  109. def with_state(
  110. storage: "StorageControllers",
  111. state_group: Optional[int],
  112. state_group_before_event: Optional[int],
  113. state_delta_due_to_event: Optional[StateMap[str]],
  114. partial_state: bool,
  115. state_group_deltas: Dict[Tuple[int, int], StateMap[str]],
  116. ) -> "EventContext":
  117. return EventContext(
  118. storage=storage,
  119. state_group=state_group,
  120. state_group_before_event=state_group_before_event,
  121. state_delta_due_to_event=state_delta_due_to_event,
  122. state_group_deltas=state_group_deltas,
  123. partial_state=partial_state,
  124. )
  125. @staticmethod
  126. def for_outlier(
  127. storage: "StorageControllers",
  128. ) -> "EventContext":
  129. """Return an EventContext instance suitable for persisting an outlier event"""
  130. return EventContext(storage=storage, state_group_deltas={})
  131. async def persist(self, event: EventBase) -> "EventContext":
  132. return self
  133. async def serialize(self, event: EventBase, store: "DataStore") -> JsonDict:
  134. """Converts self to a type that can be serialized as JSON, and then
  135. deserialized by `deserialize`
  136. Args:
  137. event: The event that this context relates to
  138. Returns:
  139. The serialized event.
  140. """
  141. return {
  142. "state_group": self._state_group,
  143. "state_group_before_event": self.state_group_before_event,
  144. "rejected": self.rejected,
  145. "state_group_deltas": _encode_state_group_delta(self.state_group_deltas),
  146. "state_delta_due_to_event": _encode_state_dict(
  147. self._state_delta_due_to_event
  148. ),
  149. "app_service_id": self.app_service.id if self.app_service else None,
  150. "partial_state": self.partial_state,
  151. }
  152. @staticmethod
  153. def deserialize(storage: "StorageControllers", input: JsonDict) -> "EventContext":
  154. """Converts a dict that was produced by `serialize` back into a
  155. EventContext.
  156. Args:
  157. storage: Used to convert AS ID to AS object and fetch state.
  158. input: A dict produced by `serialize`
  159. Returns:
  160. The event context.
  161. """
  162. context = EventContext(
  163. # We use the state_group and prev_state_id stuff to pull the
  164. # current_state_ids out of the DB and construct prev_state_ids.
  165. storage=storage,
  166. state_group=input["state_group"],
  167. state_group_before_event=input["state_group_before_event"],
  168. state_group_deltas=_decode_state_group_delta(input["state_group_deltas"]),
  169. state_delta_due_to_event=_decode_state_dict(
  170. input["state_delta_due_to_event"]
  171. ),
  172. rejected=input["rejected"],
  173. partial_state=input.get("partial_state", False),
  174. )
  175. app_service_id = input["app_service_id"]
  176. if app_service_id:
  177. context.app_service = storage.main.get_app_service_by_id(app_service_id)
  178. return context
  179. @property
  180. def state_group(self) -> Optional[int]:
  181. """The ID of the state group for this event.
  182. Note that state events are persisted with a state group which includes the new
  183. event, so this is effectively the state *after* the event in question.
  184. For an outlier, where we don't have the state at the event, this will be None.
  185. It is an error to access this for a rejected event, since rejected state should
  186. not make it into the room state. Accessing this property will raise an exception
  187. if ``rejected`` is set.
  188. """
  189. if self.rejected:
  190. raise RuntimeError("Attempt to access state_group of rejected event")
  191. return self._state_group
  192. @trace
  193. @tag_args
  194. async def get_current_state_ids(
  195. self, state_filter: Optional["StateFilter"] = None
  196. ) -> Optional[StateMap[str]]:
  197. """
  198. Gets the room state map, including this event - ie, the state in ``state_group``
  199. It is an error to access this for a rejected event, since rejected state should
  200. not make it into the room state. This method will raise an exception if
  201. ``rejected`` is set.
  202. Arg:
  203. state_filter: specifies the type of state event to fetch from DB, example: EventTypes.JoinRules
  204. Returns:
  205. Returns None if state_group is None, which happens when the associated
  206. event is an outlier.
  207. Maps a (type, state_key) to the event ID of the state event matching
  208. this tuple.
  209. """
  210. if self.rejected:
  211. raise RuntimeError("Attempt to access state_ids of rejected event")
  212. assert self._state_delta_due_to_event is not None
  213. prev_state_ids = await self.get_prev_state_ids(state_filter)
  214. if self._state_delta_due_to_event:
  215. prev_state_ids = dict(prev_state_ids)
  216. prev_state_ids.update(self._state_delta_due_to_event)
  217. return prev_state_ids
  218. @trace
  219. @tag_args
  220. async def get_prev_state_ids(
  221. self, state_filter: Optional["StateFilter"] = None
  222. ) -> StateMap[str]:
  223. """
  224. Gets the room state map, excluding this event.
  225. For a non-state event, this will be the same as get_current_state_ids().
  226. Args:
  227. state_filter: specifies the type of state event to fetch from DB, example: EventTypes.JoinRules
  228. Returns:
  229. Returns {} if state_group is None, which happens when the associated
  230. event is an outlier.
  231. Maps a (type, state_key) to the event ID of the state event matching
  232. this tuple.
  233. """
  234. assert self.state_group_before_event is not None
  235. return await self._storage.state.get_state_ids_for_group(
  236. self.state_group_before_event, state_filter
  237. )
  238. @attr.s(slots=True, auto_attribs=True)
  239. class UnpersistedEventContext(UnpersistedEventContextBase):
  240. """
  241. The event context holds information about the state groups for an event. It is important
  242. to remember that an event technically has two state groups: the state group before the
  243. event, and the state group after the event. If the event is not a state event, the state
  244. group will not change (ie the state group before the event will be the same as the state
  245. group after the event), but if it is a state event the state group before the event
  246. will differ from the state group after the event.
  247. This is a version of an EventContext before the new state group (if any) has been
  248. computed and stored. It contains information about the state before the event (which
  249. also may be the information after the event, if the event is not a state event). The
  250. UnpersistedEventContext must be converted into an EventContext by calling the method
  251. 'persist' on it before it is suitable to be sent to the DB for processing.
  252. state_group_after_event:
  253. The state group after the event. This will always be None until it is persisted.
  254. If the event is not a state event, this will be the same as
  255. state_group_before_event.
  256. state_group_before_event:
  257. The ID of the state group representing the state of the room before this event.
  258. state_delta_due_to_event:
  259. If the event is a state event, then this is the delta of the state between
  260. `state_group` and `state_group_before_event`
  261. prev_group_for_state_group_before_event:
  262. If it is known, ``state_group_before_event``'s previous state group.
  263. delta_ids_to_state_group_before_event:
  264. If ``prev_group_for_state_group_before_event`` is not None, the state delta
  265. between ``prev_group_for_state_group_before_event`` and ``state_group_before_event``.
  266. partial_state:
  267. Whether the event has partial state.
  268. state_map_before_event:
  269. A map of the state before the event, i.e. the state at `state_group_before_event`
  270. """
  271. _storage: "StorageControllers"
  272. state_group_before_event: Optional[int]
  273. state_group_after_event: Optional[int]
  274. state_delta_due_to_event: Optional[StateMap[str]]
  275. prev_group_for_state_group_before_event: Optional[int]
  276. delta_ids_to_state_group_before_event: Optional[StateMap[str]]
  277. partial_state: bool
  278. state_map_before_event: Optional[StateMap[str]] = None
  279. @classmethod
  280. async def batch_persist_unpersisted_contexts(
  281. cls,
  282. events_and_context: List[Tuple[EventBase, "UnpersistedEventContextBase"]],
  283. room_id: str,
  284. last_known_state_group: int,
  285. datastore: "StateGroupDataStore",
  286. ) -> List[Tuple[EventBase, EventContext]]:
  287. """
  288. Takes a list of events and their associated unpersisted contexts and persists
  289. the unpersisted contexts, returning a list of events and persisted contexts.
  290. Note that all the events must be in a linear chain (ie a <- b <- c).
  291. Args:
  292. events_and_context: A list of events and their unpersisted contexts
  293. room_id: the room_id for the events
  294. last_known_state_group: the last persisted state group
  295. datastore: a state datastore
  296. """
  297. amended_events_and_context = await datastore.store_state_deltas_for_batched(
  298. events_and_context, room_id, last_known_state_group
  299. )
  300. events_and_persisted_context = []
  301. for event, unpersisted_context in amended_events_and_context:
  302. state_group_deltas = unpersisted_context._build_state_group_deltas()
  303. context = EventContext(
  304. storage=unpersisted_context._storage,
  305. state_group=unpersisted_context.state_group_after_event,
  306. state_group_before_event=unpersisted_context.state_group_before_event,
  307. state_delta_due_to_event=unpersisted_context.state_delta_due_to_event,
  308. partial_state=unpersisted_context.partial_state,
  309. state_group_deltas=state_group_deltas,
  310. )
  311. events_and_persisted_context.append((event, context))
  312. return events_and_persisted_context
  313. async def get_prev_state_ids(
  314. self, state_filter: Optional["StateFilter"] = None
  315. ) -> StateMap[str]:
  316. """
  317. Gets the room state map, excluding this event.
  318. Args:
  319. state_filter: specifies the type of state event to fetch from DB
  320. Returns:
  321. Maps a (type, state_key) to the event ID of the state event matching
  322. this tuple.
  323. """
  324. if self.state_map_before_event:
  325. return self.state_map_before_event
  326. assert self.state_group_before_event is not None
  327. return await self._storage.state.get_state_ids_for_group(
  328. self.state_group_before_event, state_filter
  329. )
  330. async def persist(self, event: EventBase) -> EventContext:
  331. """
  332. Creates a full `EventContext` for the event, persisting any referenced state that
  333. has not yet been persisted.
  334. Args:
  335. event: event that the EventContext is associated with.
  336. Returns: An EventContext suitable for sending to the database with the event
  337. for persisting
  338. """
  339. assert self.partial_state is not None
  340. # If we have a full set of state for before the event but don't have a state
  341. # group for that state, we need to get one
  342. if self.state_group_before_event is None:
  343. assert self.state_map_before_event
  344. state_group_before_event = await self._storage.state.store_state_group(
  345. event.event_id,
  346. event.room_id,
  347. prev_group=self.prev_group_for_state_group_before_event,
  348. delta_ids=self.delta_ids_to_state_group_before_event,
  349. current_state_ids=self.state_map_before_event,
  350. )
  351. self.state_group_before_event = state_group_before_event
  352. # if the event isn't a state event the state group doesn't change
  353. if not self.state_delta_due_to_event:
  354. self.state_group_after_event = self.state_group_before_event
  355. # otherwise if it is a state event we need to get a state group for it
  356. else:
  357. self.state_group_after_event = await self._storage.state.store_state_group(
  358. event.event_id,
  359. event.room_id,
  360. prev_group=self.state_group_before_event,
  361. delta_ids=self.state_delta_due_to_event,
  362. current_state_ids=None,
  363. )
  364. state_group_deltas = self._build_state_group_deltas()
  365. return EventContext.with_state(
  366. storage=self._storage,
  367. state_group=self.state_group_after_event,
  368. state_group_before_event=self.state_group_before_event,
  369. state_delta_due_to_event=self.state_delta_due_to_event,
  370. state_group_deltas=state_group_deltas,
  371. partial_state=self.partial_state,
  372. )
  373. def _build_state_group_deltas(self) -> Dict[Tuple[int, int], StateMap]:
  374. """
  375. Collect deltas between the state groups associated with this context
  376. """
  377. state_group_deltas = {}
  378. # if we know the state group before the event and after the event, add them and the
  379. # state delta between them to state_group_deltas
  380. if self.state_group_before_event and self.state_group_after_event:
  381. # if we have the state groups we should have the delta
  382. assert self.state_delta_due_to_event is not None
  383. state_group_deltas[
  384. (
  385. self.state_group_before_event,
  386. self.state_group_after_event,
  387. )
  388. ] = self.state_delta_due_to_event
  389. # the state group before the event may also have a state group which precedes it, if
  390. # we have that and the state group before the event, add them and the state
  391. # delta between them to state_group_deltas
  392. if (
  393. self.prev_group_for_state_group_before_event
  394. and self.state_group_before_event
  395. ):
  396. # if we have both state groups we should have the delta between them
  397. assert self.delta_ids_to_state_group_before_event is not None
  398. state_group_deltas[
  399. (
  400. self.prev_group_for_state_group_before_event,
  401. self.state_group_before_event,
  402. )
  403. ] = self.delta_ids_to_state_group_before_event
  404. return state_group_deltas
  405. def _encode_state_group_delta(
  406. state_group_delta: Dict[Tuple[int, int], StateMap[str]]
  407. ) -> List[Tuple[int, int, Optional[List[Tuple[str, str, str]]]]]:
  408. if not state_group_delta:
  409. return []
  410. state_group_delta_encoded = []
  411. for key, value in state_group_delta.items():
  412. state_group_delta_encoded.append((key[0], key[1], _encode_state_dict(value)))
  413. return state_group_delta_encoded
  414. def _decode_state_group_delta(
  415. input: List[Tuple[int, int, List[Tuple[str, str, str]]]]
  416. ) -> Dict[Tuple[int, int], StateMap[str]]:
  417. if not input:
  418. return {}
  419. state_group_deltas = {}
  420. for state_group_1, state_group_2, state_dict in input:
  421. state_map = _decode_state_dict(state_dict)
  422. assert state_map is not None
  423. state_group_deltas[(state_group_1, state_group_2)] = state_map
  424. return state_group_deltas
  425. def _encode_state_dict(
  426. state_dict: Optional[StateMap[str]],
  427. ) -> Optional[List[Tuple[str, str, str]]]:
  428. """Since dicts of (type, state_key) -> event_id cannot be serialized in
  429. JSON we need to convert them to a form that can.
  430. """
  431. if state_dict is None:
  432. return None
  433. return [(etype, state_key, v) for (etype, state_key), v in state_dict.items()]
  434. def _decode_state_dict(
  435. input: Optional[List[Tuple[str, str, str]]]
  436. ) -> Optional[StateMap[str]]:
  437. """Decodes a state dict encoded using `_encode_state_dict` above"""
  438. if input is None:
  439. return None
  440. return immutabledict({(etype, state_key): v for etype, state_key, v in input})