test_state.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014 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 tests import unittest
  16. from twisted.internet import defer
  17. from synapse.events import FrozenEvent
  18. from synapse.api.auth import Auth
  19. from synapse.api.constants import EventTypes, Membership
  20. from synapse.state import StateHandler
  21. from .utils import MockClock
  22. from mock import Mock
  23. _next_event_id = 1000
  24. def create_event(name=None, type=None, state_key=None, depth=2, event_id=None,
  25. prev_events=[], **kwargs):
  26. global _next_event_id
  27. if not event_id:
  28. _next_event_id += 1
  29. event_id = "$%s:test" % (_next_event_id,)
  30. if not name:
  31. if state_key is not None:
  32. name = "<%s-%s, %s>" % (type, state_key, event_id,)
  33. else:
  34. name = "<%s, %s>" % (type, event_id,)
  35. d = {
  36. "event_id": event_id,
  37. "type": type,
  38. "sender": "@user_id:example.com",
  39. "room_id": "!room_id:example.com",
  40. "depth": depth,
  41. "prev_events": prev_events,
  42. }
  43. if state_key is not None:
  44. d["state_key"] = state_key
  45. d.update(kwargs)
  46. event = FrozenEvent(d)
  47. return event
  48. class StateGroupStore(object):
  49. def __init__(self):
  50. self._event_to_state_group = {}
  51. self._group_to_state = {}
  52. self._next_group = 1
  53. def get_state_groups(self, room_id, event_ids):
  54. groups = {}
  55. for event_id in event_ids:
  56. group = self._event_to_state_group.get(event_id)
  57. if group:
  58. groups[group] = self._group_to_state[group]
  59. return defer.succeed(groups)
  60. def store_state_groups(self, event, context):
  61. if context.current_state is None:
  62. return
  63. state_events = context.current_state
  64. if event.is_state():
  65. state_events[(event.type, event.state_key)] = event
  66. state_group = context.state_group
  67. if not state_group:
  68. state_group = self._next_group
  69. self._next_group += 1
  70. self._group_to_state[state_group] = state_events.values()
  71. self._event_to_state_group[event.event_id] = state_group
  72. class DictObj(dict):
  73. def __init__(self, **kwargs):
  74. super(DictObj, self).__init__(kwargs)
  75. self.__dict__ = self
  76. class Graph(object):
  77. def __init__(self, nodes, edges):
  78. events = {}
  79. clobbered = set(events.keys())
  80. for event_id, fields in nodes.items():
  81. refs = edges.get(event_id)
  82. if refs:
  83. clobbered.difference_update(refs)
  84. prev_events = [(r, {}) for r in refs]
  85. else:
  86. prev_events = []
  87. events[event_id] = create_event(
  88. event_id=event_id,
  89. prev_events=prev_events,
  90. **fields
  91. )
  92. self._leaves = clobbered
  93. self._events = sorted(events.values(), key=lambda e: e.depth)
  94. def walk(self):
  95. return iter(self._events)
  96. def get_leaves(self):
  97. return (self._events[i] for i in self._leaves)
  98. class StateTestCase(unittest.TestCase):
  99. def setUp(self):
  100. self.store = Mock(
  101. spec_set=[
  102. "get_state_groups",
  103. "add_event_hashes",
  104. ]
  105. )
  106. hs = Mock(spec=[
  107. "get_datastore", "get_auth", "get_state_handler", "get_clock",
  108. ])
  109. hs.get_datastore.return_value = self.store
  110. hs.get_state_handler.return_value = None
  111. hs.get_auth.return_value = Auth(hs)
  112. hs.get_clock.return_value = MockClock()
  113. self.state = StateHandler(hs)
  114. self.event_id = 0
  115. @defer.inlineCallbacks
  116. def test_branch_no_conflict(self):
  117. graph = Graph(
  118. nodes={
  119. "START": DictObj(
  120. type=EventTypes.Create,
  121. state_key="",
  122. depth=1,
  123. ),
  124. "A": DictObj(
  125. type=EventTypes.Message,
  126. depth=2,
  127. ),
  128. "B": DictObj(
  129. type=EventTypes.Message,
  130. depth=3,
  131. ),
  132. "C": DictObj(
  133. type=EventTypes.Name,
  134. state_key="",
  135. depth=3,
  136. ),
  137. "D": DictObj(
  138. type=EventTypes.Message,
  139. depth=4,
  140. ),
  141. },
  142. edges={
  143. "A": ["START"],
  144. "B": ["A"],
  145. "C": ["A"],
  146. "D": ["B", "C"]
  147. }
  148. )
  149. store = StateGroupStore()
  150. self.store.get_state_groups.side_effect = store.get_state_groups
  151. context_store = {}
  152. for event in graph.walk():
  153. context = yield self.state.compute_event_context(event)
  154. store.store_state_groups(event, context)
  155. context_store[event.event_id] = context
  156. self.assertEqual(2, len(context_store["D"].current_state))
  157. @defer.inlineCallbacks
  158. def test_branch_basic_conflict(self):
  159. graph = Graph(
  160. nodes={
  161. "START": DictObj(
  162. type=EventTypes.Create,
  163. state_key="",
  164. content={"creator": "@user_id:example.com"},
  165. depth=1,
  166. ),
  167. "A": DictObj(
  168. type=EventTypes.Member,
  169. state_key="@user_id:example.com",
  170. content={"membership": Membership.JOIN},
  171. membership=Membership.JOIN,
  172. depth=2,
  173. ),
  174. "B": DictObj(
  175. type=EventTypes.Name,
  176. state_key="",
  177. depth=3,
  178. ),
  179. "C": DictObj(
  180. type=EventTypes.Name,
  181. state_key="",
  182. depth=4,
  183. ),
  184. "D": DictObj(
  185. type=EventTypes.Message,
  186. depth=5,
  187. ),
  188. },
  189. edges={
  190. "A": ["START"],
  191. "B": ["A"],
  192. "C": ["A"],
  193. "D": ["B", "C"]
  194. }
  195. )
  196. store = StateGroupStore()
  197. self.store.get_state_groups.side_effect = store.get_state_groups
  198. context_store = {}
  199. for event in graph.walk():
  200. context = yield self.state.compute_event_context(event)
  201. store.store_state_groups(event, context)
  202. context_store[event.event_id] = context
  203. self.assertSetEqual(
  204. {"START", "A", "C"},
  205. {e.event_id for e in context_store["D"].current_state.values()}
  206. )
  207. @defer.inlineCallbacks
  208. def test_branch_have_banned_conflict(self):
  209. graph = Graph(
  210. nodes={
  211. "START": DictObj(
  212. type=EventTypes.Create,
  213. state_key="",
  214. content={"creator": "@user_id:example.com"},
  215. depth=1,
  216. ),
  217. "A": DictObj(
  218. type=EventTypes.Member,
  219. state_key="@user_id:example.com",
  220. content={"membership": Membership.JOIN},
  221. membership=Membership.JOIN,
  222. depth=2,
  223. ),
  224. "B": DictObj(
  225. type=EventTypes.Name,
  226. state_key="",
  227. depth=3,
  228. ),
  229. "C": DictObj(
  230. type=EventTypes.Member,
  231. state_key="@user_id_2:example.com",
  232. content={"membership": Membership.BAN},
  233. membership=Membership.BAN,
  234. depth=4,
  235. ),
  236. "D": DictObj(
  237. type=EventTypes.Name,
  238. state_key="",
  239. depth=4,
  240. sender="@user_id_2:example.com",
  241. ),
  242. "E": DictObj(
  243. type=EventTypes.Message,
  244. depth=5,
  245. ),
  246. },
  247. edges={
  248. "A": ["START"],
  249. "B": ["A"],
  250. "C": ["B"],
  251. "D": ["B"],
  252. "E": ["C", "D"]
  253. }
  254. )
  255. store = StateGroupStore()
  256. self.store.get_state_groups.side_effect = store.get_state_groups
  257. context_store = {}
  258. for event in graph.walk():
  259. context = yield self.state.compute_event_context(event)
  260. store.store_state_groups(event, context)
  261. context_store[event.event_id] = context
  262. self.assertSetEqual(
  263. {"START", "A", "B", "C"},
  264. {e.event_id for e in context_store["E"].current_state.values()}
  265. )
  266. @defer.inlineCallbacks
  267. def test_annotate_with_old_message(self):
  268. event = create_event(type="test_message", name="event")
  269. old_state = [
  270. create_event(type="test1", state_key="1"),
  271. create_event(type="test1", state_key="2"),
  272. create_event(type="test2", state_key=""),
  273. ]
  274. context = yield self.state.compute_event_context(
  275. event, old_state=old_state
  276. )
  277. for k, v in context.current_state.items():
  278. type, state_key = k
  279. self.assertEqual(type, v.type)
  280. self.assertEqual(state_key, v.state_key)
  281. self.assertEqual(
  282. set(old_state), set(context.current_state.values())
  283. )
  284. self.assertIsNone(context.state_group)
  285. @defer.inlineCallbacks
  286. def test_annotate_with_old_state(self):
  287. event = create_event(type="state", state_key="", name="event")
  288. old_state = [
  289. create_event(type="test1", state_key="1"),
  290. create_event(type="test1", state_key="2"),
  291. create_event(type="test2", state_key=""),
  292. ]
  293. context = yield self.state.compute_event_context(
  294. event, old_state=old_state
  295. )
  296. for k, v in context.current_state.items():
  297. type, state_key = k
  298. self.assertEqual(type, v.type)
  299. self.assertEqual(state_key, v.state_key)
  300. self.assertEqual(
  301. set(old_state),
  302. set(context.current_state.values())
  303. )
  304. self.assertIsNone(context.state_group)
  305. @defer.inlineCallbacks
  306. def test_trivial_annotate_message(self):
  307. event = create_event(type="test_message", name="event")
  308. old_state = [
  309. create_event(type="test1", state_key="1"),
  310. create_event(type="test1", state_key="2"),
  311. create_event(type="test2", state_key=""),
  312. ]
  313. group_name = "group_name_1"
  314. self.store.get_state_groups.return_value = {
  315. group_name: old_state,
  316. }
  317. context = yield self.state.compute_event_context(event)
  318. for k, v in context.current_state.items():
  319. type, state_key = k
  320. self.assertEqual(type, v.type)
  321. self.assertEqual(state_key, v.state_key)
  322. self.assertEqual(
  323. set([e.event_id for e in old_state]),
  324. set([e.event_id for e in context.current_state.values()])
  325. )
  326. self.assertEqual(group_name, context.state_group)
  327. @defer.inlineCallbacks
  328. def test_trivial_annotate_state(self):
  329. event = create_event(type="state", state_key="", name="event")
  330. old_state = [
  331. create_event(type="test1", state_key="1"),
  332. create_event(type="test1", state_key="2"),
  333. create_event(type="test2", state_key=""),
  334. ]
  335. group_name = "group_name_1"
  336. self.store.get_state_groups.return_value = {
  337. group_name: old_state,
  338. }
  339. context = yield self.state.compute_event_context(event)
  340. for k, v in context.current_state.items():
  341. type, state_key = k
  342. self.assertEqual(type, v.type)
  343. self.assertEqual(state_key, v.state_key)
  344. self.assertEqual(
  345. set([e.event_id for e in old_state]),
  346. set([e.event_id for e in context.current_state.values()])
  347. )
  348. self.assertIsNone(context.state_group)
  349. @defer.inlineCallbacks
  350. def test_resolve_message_conflict(self):
  351. event = create_event(type="test_message", name="event")
  352. creation = create_event(
  353. type=EventTypes.Create, state_key=""
  354. )
  355. old_state_1 = [
  356. creation,
  357. create_event(type="test1", state_key="1"),
  358. create_event(type="test1", state_key="2"),
  359. create_event(type="test2", state_key=""),
  360. ]
  361. old_state_2 = [
  362. creation,
  363. create_event(type="test1", state_key="1"),
  364. create_event(type="test3", state_key="2"),
  365. create_event(type="test4", state_key=""),
  366. ]
  367. context = yield self._get_context(event, old_state_1, old_state_2)
  368. self.assertEqual(len(context.current_state), 6)
  369. self.assertIsNone(context.state_group)
  370. @defer.inlineCallbacks
  371. def test_resolve_state_conflict(self):
  372. event = create_event(type="test4", state_key="", name="event")
  373. creation = create_event(
  374. type=EventTypes.Create, state_key=""
  375. )
  376. old_state_1 = [
  377. creation,
  378. create_event(type="test1", state_key="1"),
  379. create_event(type="test1", state_key="2"),
  380. create_event(type="test2", state_key=""),
  381. ]
  382. old_state_2 = [
  383. creation,
  384. create_event(type="test1", state_key="1"),
  385. create_event(type="test3", state_key="2"),
  386. create_event(type="test4", state_key=""),
  387. ]
  388. context = yield self._get_context(event, old_state_1, old_state_2)
  389. self.assertEqual(len(context.current_state), 6)
  390. self.assertIsNone(context.state_group)
  391. @defer.inlineCallbacks
  392. def test_standard_depth_conflict(self):
  393. event = create_event(type="test4", name="event")
  394. member_event = create_event(
  395. type=EventTypes.Member,
  396. state_key="@user_id:example.com",
  397. content={
  398. "membership": Membership.JOIN,
  399. }
  400. )
  401. creation = create_event(
  402. type=EventTypes.Create, state_key="",
  403. content={"creator": "@foo:bar"}
  404. )
  405. old_state_1 = [
  406. creation,
  407. member_event,
  408. create_event(type="test1", state_key="1", depth=1),
  409. ]
  410. old_state_2 = [
  411. creation,
  412. member_event,
  413. create_event(type="test1", state_key="1", depth=2),
  414. ]
  415. context = yield self._get_context(event, old_state_1, old_state_2)
  416. self.assertEqual(old_state_2[2], context.current_state[("test1", "1")])
  417. # Reverse the depth to make sure we are actually using the depths
  418. # during state resolution.
  419. old_state_1 = [
  420. creation,
  421. member_event,
  422. create_event(type="test1", state_key="1", depth=2),
  423. ]
  424. old_state_2 = [
  425. creation,
  426. member_event,
  427. create_event(type="test1", state_key="1", depth=1),
  428. ]
  429. context = yield self._get_context(event, old_state_1, old_state_2)
  430. self.assertEqual(old_state_1[2], context.current_state[("test1", "1")])
  431. def _get_context(self, event, old_state_1, old_state_2):
  432. group_name_1 = "group_name_1"
  433. group_name_2 = "group_name_2"
  434. self.store.get_state_groups.return_value = {
  435. group_name_1: old_state_1,
  436. group_name_2: old_state_2,
  437. }
  438. return self.state.compute_event_context(event)