snapshot.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  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. from six import iteritems
  16. from frozendict import frozendict
  17. from twisted.internet import defer
  18. from synapse.logging.context import make_deferred_yieldable, run_in_background
  19. class EventContext(object):
  20. """
  21. Attributes:
  22. state_group (int|None): state group id, if the state has been stored
  23. as a state group. This is usually only None if e.g. the event is
  24. an outlier.
  25. rejected (bool|str): A rejection reason if the event was rejected, else
  26. False
  27. push_actions (list[(str, list[object])]): list of (user_id, actions)
  28. tuples
  29. prev_group (int): Previously persisted state group. ``None`` for an
  30. outlier.
  31. delta_ids (dict[(str, str), str]): Delta from ``prev_group``.
  32. (type, state_key) -> event_id. ``None`` for an outlier.
  33. prev_state_events (?): XXX: is this ever set to anything other than
  34. the empty list?
  35. _current_state_ids (dict[(str, str), str]|None):
  36. The current state map including the current event. None if outlier
  37. or we haven't fetched the state from DB yet.
  38. (type, state_key) -> event_id
  39. _prev_state_ids (dict[(str, str), str]|None):
  40. The current state map excluding the current event. None if outlier
  41. or we haven't fetched the state from DB yet.
  42. (type, state_key) -> event_id
  43. _fetching_state_deferred (Deferred|None): Resolves when *_state_ids have
  44. been calculated. None if we haven't started calculating yet
  45. _event_type (str): The type of the event the context is associated with.
  46. Only set when state has not been fetched yet.
  47. _event_state_key (str|None): The state_key of the event the context is
  48. associated with. Only set when state has not been fetched yet.
  49. _prev_state_id (str|None): If the event associated with the context is
  50. a state event, then `_prev_state_id` is the event_id of the state
  51. that was replaced.
  52. Only set when state has not been fetched yet.
  53. """
  54. __slots__ = [
  55. "state_group",
  56. "rejected",
  57. "prev_group",
  58. "delta_ids",
  59. "prev_state_events",
  60. "app_service",
  61. "_current_state_ids",
  62. "_prev_state_ids",
  63. "_prev_state_id",
  64. "_event_type",
  65. "_event_state_key",
  66. "_fetching_state_deferred",
  67. ]
  68. def __init__(self):
  69. self.prev_state_events = []
  70. self.rejected = False
  71. self.app_service = None
  72. @staticmethod
  73. def with_state(
  74. state_group, current_state_ids, prev_state_ids, prev_group=None, delta_ids=None
  75. ):
  76. context = EventContext()
  77. # The current state including the current event
  78. context._current_state_ids = current_state_ids
  79. # The current state excluding the current event
  80. context._prev_state_ids = prev_state_ids
  81. context.state_group = state_group
  82. context._prev_state_id = None
  83. context._event_type = None
  84. context._event_state_key = None
  85. context._fetching_state_deferred = defer.succeed(None)
  86. # A previously persisted state group and a delta between that
  87. # and this state.
  88. context.prev_group = prev_group
  89. context.delta_ids = delta_ids
  90. return context
  91. @defer.inlineCallbacks
  92. def serialize(self, event, store):
  93. """Converts self to a type that can be serialized as JSON, and then
  94. deserialized by `deserialize`
  95. Args:
  96. event (FrozenEvent): The event that this context relates to
  97. Returns:
  98. dict
  99. """
  100. # We don't serialize the full state dicts, instead they get pulled out
  101. # of the DB on the other side. However, the other side can't figure out
  102. # the prev_state_ids, so if we're a state event we include the event
  103. # id that we replaced in the state.
  104. if event.is_state():
  105. prev_state_ids = yield self.get_prev_state_ids(store)
  106. prev_state_id = prev_state_ids.get((event.type, event.state_key))
  107. else:
  108. prev_state_id = None
  109. return {
  110. "prev_state_id": prev_state_id,
  111. "event_type": event.type,
  112. "event_state_key": event.state_key if event.is_state() else None,
  113. "state_group": self.state_group,
  114. "rejected": self.rejected,
  115. "prev_group": self.prev_group,
  116. "delta_ids": _encode_state_dict(self.delta_ids),
  117. "prev_state_events": self.prev_state_events,
  118. "app_service_id": self.app_service.id if self.app_service else None,
  119. }
  120. @staticmethod
  121. def deserialize(store, input):
  122. """Converts a dict that was produced by `serialize` back into a
  123. EventContext.
  124. Args:
  125. store (DataStore): Used to convert AS ID to AS object
  126. input (dict): A dict produced by `serialize`
  127. Returns:
  128. EventContext
  129. """
  130. context = EventContext()
  131. # We use the state_group and prev_state_id stuff to pull the
  132. # current_state_ids out of the DB and construct prev_state_ids.
  133. context._prev_state_id = input["prev_state_id"]
  134. context._event_type = input["event_type"]
  135. context._event_state_key = input["event_state_key"]
  136. context._current_state_ids = None
  137. context._prev_state_ids = None
  138. context._fetching_state_deferred = None
  139. context.state_group = input["state_group"]
  140. context.prev_group = input["prev_group"]
  141. context.delta_ids = _decode_state_dict(input["delta_ids"])
  142. context.rejected = input["rejected"]
  143. context.prev_state_events = input["prev_state_events"]
  144. app_service_id = input["app_service_id"]
  145. if app_service_id:
  146. context.app_service = store.get_app_service_by_id(app_service_id)
  147. return context
  148. @defer.inlineCallbacks
  149. def get_current_state_ids(self, store):
  150. """Gets the current state IDs
  151. Returns:
  152. Deferred[dict[(str, str), str]|None]: Returns None if state_group
  153. is None, which happens when the associated event is an outlier.
  154. Maps a (type, state_key) to the event ID of the state event matching
  155. this tuple.
  156. """
  157. if not self._fetching_state_deferred:
  158. self._fetching_state_deferred = run_in_background(
  159. self._fill_out_state, store
  160. )
  161. yield make_deferred_yieldable(self._fetching_state_deferred)
  162. return self._current_state_ids
  163. @defer.inlineCallbacks
  164. def get_prev_state_ids(self, store):
  165. """Gets the prev state IDs
  166. Returns:
  167. Deferred[dict[(str, str), str]|None]: Returns None if state_group
  168. is None, which happens when the associated event is an outlier.
  169. Maps a (type, state_key) to the event ID of the state event matching
  170. this tuple.
  171. """
  172. if not self._fetching_state_deferred:
  173. self._fetching_state_deferred = run_in_background(
  174. self._fill_out_state, store
  175. )
  176. yield make_deferred_yieldable(self._fetching_state_deferred)
  177. return self._prev_state_ids
  178. def get_cached_current_state_ids(self):
  179. """Gets the current state IDs if we have them already cached.
  180. Returns:
  181. dict[(str, str), str]|None: Returns None if we haven't cached the
  182. state or if state_group is None, which happens when the associated
  183. event is an outlier.
  184. """
  185. return self._current_state_ids
  186. @defer.inlineCallbacks
  187. def _fill_out_state(self, store):
  188. """Called to populate the _current_state_ids and _prev_state_ids
  189. attributes by loading from the database.
  190. """
  191. if self.state_group is None:
  192. return
  193. self._current_state_ids = yield store.get_state_ids_for_group(self.state_group)
  194. if self._prev_state_id and self._event_state_key is not None:
  195. self._prev_state_ids = dict(self._current_state_ids)
  196. key = (self._event_type, self._event_state_key)
  197. self._prev_state_ids[key] = self._prev_state_id
  198. else:
  199. self._prev_state_ids = self._current_state_ids
  200. @defer.inlineCallbacks
  201. def update_state(
  202. self, state_group, prev_state_ids, current_state_ids, prev_group, delta_ids
  203. ):
  204. """Replace the state in the context
  205. """
  206. # We need to make sure we wait for any ongoing fetching of state
  207. # to complete so that the updated state doesn't get clobbered
  208. if self._fetching_state_deferred:
  209. yield make_deferred_yieldable(self._fetching_state_deferred)
  210. self.state_group = state_group
  211. self._prev_state_ids = prev_state_ids
  212. self.prev_group = prev_group
  213. self._current_state_ids = current_state_ids
  214. self.delta_ids = delta_ids
  215. # We need to ensure that that we've marked as having fetched the state
  216. self._fetching_state_deferred = defer.succeed(None)
  217. def _encode_state_dict(state_dict):
  218. """Since dicts of (type, state_key) -> event_id cannot be serialized in
  219. JSON we need to convert them to a form that can.
  220. """
  221. if state_dict is None:
  222. return None
  223. return [(etype, state_key, v) for (etype, state_key), v in iteritems(state_dict)]
  224. def _decode_state_dict(input):
  225. """Decodes a state dict encoded using `_encode_state_dict` above
  226. """
  227. if input is None:
  228. return None
  229. return frozendict({(etype, state_key): v for etype, state_key, v in input})