snapshot.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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 frozendict import frozendict
  16. from twisted.internet import defer
  17. class EventContext(object):
  18. """
  19. Attributes:
  20. current_state_ids (dict[(str, str), str]):
  21. The current state map including the current event.
  22. (type, state_key) -> event_id
  23. prev_state_ids (dict[(str, str), str]):
  24. The current state map excluding the current event.
  25. (type, state_key) -> event_id
  26. state_group (int|None): state group id, if the state has been stored
  27. as a state group. This is usually only None if e.g. the event is
  28. an outlier.
  29. rejected (bool|str): A rejection reason if the event was rejected, else
  30. False
  31. push_actions (list[(str, list[object])]): list of (user_id, actions)
  32. tuples
  33. prev_group (int): Previously persisted state group. ``None`` for an
  34. outlier.
  35. delta_ids (dict[(str, str), str]): Delta from ``prev_group``.
  36. (type, state_key) -> event_id. ``None`` for an outlier.
  37. prev_state_events (?): XXX: is this ever set to anything other than
  38. the empty list?
  39. """
  40. __slots__ = [
  41. "current_state_ids",
  42. "prev_state_ids",
  43. "state_group",
  44. "rejected",
  45. "prev_group",
  46. "delta_ids",
  47. "prev_state_events",
  48. "app_service",
  49. ]
  50. def __init__(self):
  51. # The current state including the current event
  52. self.current_state_ids = None
  53. # The current state excluding the current event
  54. self.prev_state_ids = None
  55. self.state_group = None
  56. self.rejected = False
  57. # A previously persisted state group and a delta between that
  58. # and this state.
  59. self.prev_group = None
  60. self.delta_ids = None
  61. self.prev_state_events = None
  62. self.app_service = None
  63. def serialize(self, event):
  64. """Converts self to a type that can be serialized as JSON, and then
  65. deserialized by `deserialize`
  66. Args:
  67. event (FrozenEvent): The event that this context relates to
  68. Returns:
  69. dict
  70. """
  71. # We don't serialize the full state dicts, instead they get pulled out
  72. # of the DB on the other side. However, the other side can't figure out
  73. # the prev_state_ids, so if we're a state event we include the event
  74. # id that we replaced in the state.
  75. if event.is_state():
  76. prev_state_id = self.prev_state_ids.get((event.type, event.state_key))
  77. else:
  78. prev_state_id = None
  79. return {
  80. "prev_state_id": prev_state_id,
  81. "event_type": event.type,
  82. "event_state_key": event.state_key if event.is_state() else None,
  83. "state_group": self.state_group,
  84. "rejected": self.rejected,
  85. "prev_group": self.prev_group,
  86. "delta_ids": _encode_state_dict(self.delta_ids),
  87. "prev_state_events": self.prev_state_events,
  88. "app_service_id": self.app_service.id if self.app_service else None
  89. }
  90. @staticmethod
  91. @defer.inlineCallbacks
  92. def deserialize(store, input):
  93. """Converts a dict that was produced by `serialize` back into a
  94. EventContext.
  95. Args:
  96. store (DataStore): Used to convert AS ID to AS object
  97. input (dict): A dict produced by `serialize`
  98. Returns:
  99. EventContext
  100. """
  101. context = EventContext()
  102. context.state_group = input["state_group"]
  103. context.rejected = input["rejected"]
  104. context.prev_group = input["prev_group"]
  105. context.delta_ids = _decode_state_dict(input["delta_ids"])
  106. context.prev_state_events = input["prev_state_events"]
  107. # We use the state_group and prev_state_id stuff to pull the
  108. # current_state_ids out of the DB and construct prev_state_ids.
  109. prev_state_id = input["prev_state_id"]
  110. event_type = input["event_type"]
  111. event_state_key = input["event_state_key"]
  112. context.current_state_ids = yield store.get_state_ids_for_group(
  113. context.state_group,
  114. )
  115. if prev_state_id and event_state_key:
  116. context.prev_state_ids = dict(context.current_state_ids)
  117. context.prev_state_ids[(event_type, event_state_key)] = prev_state_id
  118. else:
  119. context.prev_state_ids = context.current_state_ids
  120. app_service_id = input["app_service_id"]
  121. if app_service_id:
  122. context.app_service = store.get_app_service_by_id(app_service_id)
  123. defer.returnValue(context)
  124. def _encode_state_dict(state_dict):
  125. """Since dicts of (type, state_key) -> event_id cannot be serialized in
  126. JSON we need to convert them to a form that can.
  127. """
  128. if state_dict is None:
  129. return None
  130. return [
  131. (etype, state_key, v)
  132. for (etype, state_key), v in state_dict.iteritems()
  133. ]
  134. def _decode_state_dict(input):
  135. """Decodes a state dict encoded using `_encode_state_dict` above
  136. """
  137. if input is None:
  138. return None
  139. return frozendict({(etype, state_key,): v for etype, state_key, v in input})