snapshot.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. defer.returnValue(
  110. {
  111. "prev_state_id": prev_state_id,
  112. "event_type": event.type,
  113. "event_state_key": event.state_key if event.is_state() else None,
  114. "state_group": self.state_group,
  115. "rejected": self.rejected,
  116. "prev_group": self.prev_group,
  117. "delta_ids": _encode_state_dict(self.delta_ids),
  118. "prev_state_events": self.prev_state_events,
  119. "app_service_id": self.app_service.id if self.app_service else None,
  120. }
  121. )
  122. @staticmethod
  123. def deserialize(store, input):
  124. """Converts a dict that was produced by `serialize` back into a
  125. EventContext.
  126. Args:
  127. store (DataStore): Used to convert AS ID to AS object
  128. input (dict): A dict produced by `serialize`
  129. Returns:
  130. EventContext
  131. """
  132. context = EventContext()
  133. # We use the state_group and prev_state_id stuff to pull the
  134. # current_state_ids out of the DB and construct prev_state_ids.
  135. context._prev_state_id = input["prev_state_id"]
  136. context._event_type = input["event_type"]
  137. context._event_state_key = input["event_state_key"]
  138. context._current_state_ids = None
  139. context._prev_state_ids = None
  140. context._fetching_state_deferred = None
  141. context.state_group = input["state_group"]
  142. context.prev_group = input["prev_group"]
  143. context.delta_ids = _decode_state_dict(input["delta_ids"])
  144. context.rejected = input["rejected"]
  145. context.prev_state_events = input["prev_state_events"]
  146. app_service_id = input["app_service_id"]
  147. if app_service_id:
  148. context.app_service = store.get_app_service_by_id(app_service_id)
  149. return context
  150. @defer.inlineCallbacks
  151. def get_current_state_ids(self, store):
  152. """Gets the current state IDs
  153. Returns:
  154. Deferred[dict[(str, str), str]|None]: Returns None if state_group
  155. is None, which happens when the associated event is an outlier.
  156. Maps a (type, state_key) to the event ID of the state event matching
  157. this tuple.
  158. """
  159. if not self._fetching_state_deferred:
  160. self._fetching_state_deferred = run_in_background(
  161. self._fill_out_state, store
  162. )
  163. yield make_deferred_yieldable(self._fetching_state_deferred)
  164. defer.returnValue(self._current_state_ids)
  165. @defer.inlineCallbacks
  166. def get_prev_state_ids(self, store):
  167. """Gets the prev state IDs
  168. Returns:
  169. Deferred[dict[(str, str), str]|None]: Returns None if state_group
  170. is None, which happens when the associated event is an outlier.
  171. Maps a (type, state_key) to the event ID of the state event matching
  172. this tuple.
  173. """
  174. if not self._fetching_state_deferred:
  175. self._fetching_state_deferred = run_in_background(
  176. self._fill_out_state, store
  177. )
  178. yield make_deferred_yieldable(self._fetching_state_deferred)
  179. defer.returnValue(self._prev_state_ids)
  180. def get_cached_current_state_ids(self):
  181. """Gets the current state IDs if we have them already cached.
  182. Returns:
  183. dict[(str, str), str]|None: Returns None if we haven't cached the
  184. state or if state_group is None, which happens when the associated
  185. event is an outlier.
  186. """
  187. return self._current_state_ids
  188. @defer.inlineCallbacks
  189. def _fill_out_state(self, store):
  190. """Called to populate the _current_state_ids and _prev_state_ids
  191. attributes by loading from the database.
  192. """
  193. if self.state_group is None:
  194. return
  195. self._current_state_ids = yield store.get_state_ids_for_group(self.state_group)
  196. if self._prev_state_id and self._event_state_key is not None:
  197. self._prev_state_ids = dict(self._current_state_ids)
  198. key = (self._event_type, self._event_state_key)
  199. self._prev_state_ids[key] = self._prev_state_id
  200. else:
  201. self._prev_state_ids = self._current_state_ids
  202. @defer.inlineCallbacks
  203. def update_state(
  204. self, state_group, prev_state_ids, current_state_ids, prev_group, delta_ids
  205. ):
  206. """Replace the state in the context
  207. """
  208. # We need to make sure we wait for any ongoing fetching of state
  209. # to complete so that the updated state doesn't get clobbered
  210. if self._fetching_state_deferred:
  211. yield make_deferred_yieldable(self._fetching_state_deferred)
  212. self.state_group = state_group
  213. self._prev_state_ids = prev_state_ids
  214. self.prev_group = prev_group
  215. self._current_state_ids = current_state_ids
  216. self.delta_ids = delta_ids
  217. # We need to ensure that that we've marked as having fetched the state
  218. self._fetching_state_deferred = defer.succeed(None)
  219. def _encode_state_dict(state_dict):
  220. """Since dicts of (type, state_key) -> event_id cannot be serialized in
  221. JSON we need to convert them to a form that can.
  222. """
  223. if state_dict is None:
  224. return None
  225. return [(etype, state_key, v) for (etype, state_key), v in iteritems(state_dict)]
  226. def _decode_state_dict(input):
  227. """Decodes a state dict encoded using `_encode_state_dict` above
  228. """
  229. if input is None:
  230. return None
  231. return frozendict({(etype, state_key): v for etype, state_key, v in input})