test_state.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  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 mock import Mock
  16. from twisted.internet import defer
  17. from synapse.api.auth import Auth
  18. from synapse.api.constants import EventTypes, Membership
  19. from synapse.events import FrozenEvent
  20. from synapse.state import StateHandler, StateResolutionHandler
  21. from tests import unittest
  22. from .utils import MockClock
  23. _next_event_id = 1000
  24. def create_event(
  25. name=None,
  26. type=None,
  27. state_key=None,
  28. depth=2,
  29. event_id=None,
  30. prev_events=[],
  31. **kwargs
  32. ):
  33. global _next_event_id
  34. if not event_id:
  35. _next_event_id += 1
  36. event_id = "$%s:test" % (_next_event_id,)
  37. if not name:
  38. if state_key is not None:
  39. name = "<%s-%s, %s>" % (type, state_key, event_id)
  40. else:
  41. name = "<%s, %s>" % (type, event_id)
  42. d = {
  43. "event_id": event_id,
  44. "type": type,
  45. "sender": "@user_id:example.com",
  46. "room_id": "!room_id:example.com",
  47. "depth": depth,
  48. "prev_events": prev_events,
  49. }
  50. if state_key is not None:
  51. d["state_key"] = state_key
  52. d.update(kwargs)
  53. event = FrozenEvent(d)
  54. return event
  55. class StateGroupStore(object):
  56. def __init__(self):
  57. self._event_to_state_group = {}
  58. self._group_to_state = {}
  59. self._event_id_to_event = {}
  60. self._next_group = 1
  61. def get_state_groups_ids(self, room_id, event_ids):
  62. groups = {}
  63. for event_id in event_ids:
  64. group = self._event_to_state_group.get(event_id)
  65. if group:
  66. groups[group] = self._group_to_state[group]
  67. return defer.succeed(groups)
  68. def store_state_group(
  69. self, event_id, room_id, prev_group, delta_ids, current_state_ids
  70. ):
  71. state_group = self._next_group
  72. self._next_group += 1
  73. self._group_to_state[state_group] = dict(current_state_ids)
  74. return state_group
  75. def get_events(self, event_ids, **kwargs):
  76. return {
  77. e_id: self._event_id_to_event[e_id]
  78. for e_id in event_ids
  79. if e_id in self._event_id_to_event
  80. }
  81. def get_state_group_delta(self, name):
  82. return (None, None)
  83. def register_events(self, events):
  84. for e in events:
  85. self._event_id_to_event[e.event_id] = e
  86. def register_event_context(self, event, context):
  87. self._event_to_state_group[event.event_id] = context.state_group
  88. def register_event_id_state_group(self, event_id, state_group):
  89. self._event_to_state_group[event_id] = state_group
  90. class DictObj(dict):
  91. def __init__(self, **kwargs):
  92. super(DictObj, self).__init__(kwargs)
  93. self.__dict__ = self
  94. class Graph(object):
  95. def __init__(self, nodes, edges):
  96. events = {}
  97. clobbered = set(events.keys())
  98. for event_id, fields in nodes.items():
  99. refs = edges.get(event_id)
  100. if refs:
  101. clobbered.difference_update(refs)
  102. prev_events = [(r, {}) for r in refs]
  103. else:
  104. prev_events = []
  105. events[event_id] = create_event(
  106. event_id=event_id, prev_events=prev_events, **fields
  107. )
  108. self._leaves = clobbered
  109. self._events = sorted(events.values(), key=lambda e: e.depth)
  110. def walk(self):
  111. return iter(self._events)
  112. def get_leaves(self):
  113. return (self._events[i] for i in self._leaves)
  114. class StateTestCase(unittest.TestCase):
  115. def setUp(self):
  116. self.store = StateGroupStore()
  117. hs = Mock(
  118. spec_set=[
  119. "get_datastore",
  120. "get_auth",
  121. "get_state_handler",
  122. "get_clock",
  123. "get_state_resolution_handler",
  124. ]
  125. )
  126. hs.get_datastore.return_value = self.store
  127. hs.get_state_handler.return_value = None
  128. hs.get_clock.return_value = MockClock()
  129. hs.get_auth.return_value = Auth(hs)
  130. hs.get_state_resolution_handler = lambda: StateResolutionHandler(hs)
  131. self.state = StateHandler(hs)
  132. self.event_id = 0
  133. @defer.inlineCallbacks
  134. def test_branch_no_conflict(self):
  135. graph = Graph(
  136. nodes={
  137. "START": DictObj(type=EventTypes.Create, state_key="", depth=1),
  138. "A": DictObj(type=EventTypes.Message, depth=2),
  139. "B": DictObj(type=EventTypes.Message, depth=3),
  140. "C": DictObj(type=EventTypes.Name, state_key="", depth=3),
  141. "D": DictObj(type=EventTypes.Message, depth=4),
  142. },
  143. edges={"A": ["START"], "B": ["A"], "C": ["A"], "D": ["B", "C"]},
  144. )
  145. self.store.register_events(graph.walk())
  146. context_store = {}
  147. for event in graph.walk():
  148. context = yield self.state.compute_event_context(event)
  149. self.store.register_event_context(event, context)
  150. context_store[event.event_id] = context
  151. prev_state_ids = yield context_store["D"].get_prev_state_ids(self.store)
  152. self.assertEqual(2, len(prev_state_ids))
  153. @defer.inlineCallbacks
  154. def test_branch_basic_conflict(self):
  155. graph = Graph(
  156. nodes={
  157. "START": DictObj(
  158. type=EventTypes.Create,
  159. state_key="",
  160. content={"creator": "@user_id:example.com"},
  161. depth=1,
  162. ),
  163. "A": DictObj(
  164. type=EventTypes.Member,
  165. state_key="@user_id:example.com",
  166. content={"membership": Membership.JOIN},
  167. membership=Membership.JOIN,
  168. depth=2,
  169. ),
  170. "B": DictObj(type=EventTypes.Name, state_key="", depth=3),
  171. "C": DictObj(type=EventTypes.Name, state_key="", depth=4),
  172. "D": DictObj(type=EventTypes.Message, depth=5),
  173. },
  174. edges={"A": ["START"], "B": ["A"], "C": ["A"], "D": ["B", "C"]},
  175. )
  176. self.store.register_events(graph.walk())
  177. context_store = {}
  178. for event in graph.walk():
  179. context = yield self.state.compute_event_context(event)
  180. self.store.register_event_context(event, context)
  181. context_store[event.event_id] = context
  182. prev_state_ids = yield context_store["D"].get_prev_state_ids(self.store)
  183. self.assertSetEqual(
  184. {"START", "A", "C"}, {e_id for e_id in prev_state_ids.values()}
  185. )
  186. @defer.inlineCallbacks
  187. def test_branch_have_banned_conflict(self):
  188. graph = Graph(
  189. nodes={
  190. "START": DictObj(
  191. type=EventTypes.Create,
  192. state_key="",
  193. content={"creator": "@user_id:example.com"},
  194. depth=1,
  195. ),
  196. "A": DictObj(
  197. type=EventTypes.Member,
  198. state_key="@user_id:example.com",
  199. content={"membership": Membership.JOIN},
  200. membership=Membership.JOIN,
  201. depth=2,
  202. ),
  203. "B": DictObj(type=EventTypes.Name, state_key="", depth=3),
  204. "C": DictObj(
  205. type=EventTypes.Member,
  206. state_key="@user_id_2:example.com",
  207. content={"membership": Membership.BAN},
  208. membership=Membership.BAN,
  209. depth=4,
  210. ),
  211. "D": DictObj(
  212. type=EventTypes.Name,
  213. state_key="",
  214. depth=4,
  215. sender="@user_id_2:example.com",
  216. ),
  217. "E": DictObj(type=EventTypes.Message, depth=5),
  218. },
  219. edges={"A": ["START"], "B": ["A"], "C": ["B"], "D": ["B"], "E": ["C", "D"]},
  220. )
  221. self.store.register_events(graph.walk())
  222. context_store = {}
  223. for event in graph.walk():
  224. context = yield self.state.compute_event_context(event)
  225. self.store.register_event_context(event, context)
  226. context_store[event.event_id] = context
  227. prev_state_ids = yield context_store["E"].get_prev_state_ids(self.store)
  228. self.assertSetEqual(
  229. {"START", "A", "B", "C"}, {e for e in prev_state_ids.values()}
  230. )
  231. @defer.inlineCallbacks
  232. def test_branch_have_perms_conflict(self):
  233. userid1 = "@user_id:example.com"
  234. userid2 = "@user_id2:example.com"
  235. nodes = {
  236. "A1": DictObj(
  237. type=EventTypes.Create,
  238. state_key="",
  239. content={"creator": userid1},
  240. depth=1,
  241. ),
  242. "A2": DictObj(
  243. type=EventTypes.Member,
  244. state_key=userid1,
  245. content={"membership": Membership.JOIN},
  246. membership=Membership.JOIN,
  247. ),
  248. "A3": DictObj(
  249. type=EventTypes.Member,
  250. state_key=userid2,
  251. content={"membership": Membership.JOIN},
  252. membership=Membership.JOIN,
  253. ),
  254. "A4": DictObj(
  255. type=EventTypes.PowerLevels,
  256. state_key="",
  257. content={
  258. "events": {"m.room.name": 50},
  259. "users": {userid1: 100, userid2: 60},
  260. },
  261. ),
  262. "A5": DictObj(type=EventTypes.Name, state_key=""),
  263. "B": DictObj(
  264. type=EventTypes.PowerLevels,
  265. state_key="",
  266. content={"events": {"m.room.name": 50}, "users": {userid2: 30}},
  267. ),
  268. "C": DictObj(type=EventTypes.Name, state_key="", sender=userid2),
  269. "D": DictObj(type=EventTypes.Message),
  270. }
  271. edges = {
  272. "A2": ["A1"],
  273. "A3": ["A2"],
  274. "A4": ["A3"],
  275. "A5": ["A4"],
  276. "B": ["A5"],
  277. "C": ["A5"],
  278. "D": ["B", "C"],
  279. }
  280. self._add_depths(nodes, edges)
  281. graph = Graph(nodes, edges)
  282. self.store.register_events(graph.walk())
  283. context_store = {}
  284. for event in graph.walk():
  285. context = yield self.state.compute_event_context(event)
  286. self.store.register_event_context(event, context)
  287. context_store[event.event_id] = context
  288. prev_state_ids = yield context_store["D"].get_prev_state_ids(self.store)
  289. self.assertSetEqual(
  290. {"A1", "A2", "A3", "A5", "B"}, {e for e in prev_state_ids.values()}
  291. )
  292. def _add_depths(self, nodes, edges):
  293. def _get_depth(ev):
  294. node = nodes[ev]
  295. if 'depth' not in node:
  296. prevs = edges[ev]
  297. depth = max(_get_depth(prev) for prev in prevs) + 1
  298. node['depth'] = depth
  299. return node['depth']
  300. for n in nodes:
  301. _get_depth(n)
  302. @defer.inlineCallbacks
  303. def test_annotate_with_old_message(self):
  304. event = create_event(type="test_message", name="event")
  305. old_state = [
  306. create_event(type="test1", state_key="1"),
  307. create_event(type="test1", state_key="2"),
  308. create_event(type="test2", state_key=""),
  309. ]
  310. context = yield self.state.compute_event_context(event, old_state=old_state)
  311. current_state_ids = yield context.get_current_state_ids(self.store)
  312. self.assertEqual(
  313. set(e.event_id for e in old_state), set(current_state_ids.values())
  314. )
  315. self.assertIsNotNone(context.state_group)
  316. @defer.inlineCallbacks
  317. def test_annotate_with_old_state(self):
  318. event = create_event(type="state", state_key="", name="event")
  319. old_state = [
  320. create_event(type="test1", state_key="1"),
  321. create_event(type="test1", state_key="2"),
  322. create_event(type="test2", state_key=""),
  323. ]
  324. context = yield self.state.compute_event_context(event, old_state=old_state)
  325. prev_state_ids = yield context.get_prev_state_ids(self.store)
  326. self.assertEqual(
  327. set(e.event_id for e in old_state), set(prev_state_ids.values())
  328. )
  329. @defer.inlineCallbacks
  330. def test_trivial_annotate_message(self):
  331. prev_event_id = "prev_event_id"
  332. event = create_event(
  333. type="test_message", name="event2", prev_events=[(prev_event_id, {})]
  334. )
  335. old_state = [
  336. create_event(type="test1", state_key="1"),
  337. create_event(type="test1", state_key="2"),
  338. create_event(type="test2", state_key=""),
  339. ]
  340. group_name = self.store.store_state_group(
  341. prev_event_id,
  342. event.room_id,
  343. None,
  344. None,
  345. {(e.type, e.state_key): e.event_id for e in old_state},
  346. )
  347. self.store.register_event_id_state_group(prev_event_id, group_name)
  348. context = yield self.state.compute_event_context(event)
  349. current_state_ids = yield context.get_current_state_ids(self.store)
  350. self.assertEqual(
  351. set([e.event_id for e in old_state]), set(current_state_ids.values())
  352. )
  353. self.assertEqual(group_name, context.state_group)
  354. @defer.inlineCallbacks
  355. def test_trivial_annotate_state(self):
  356. prev_event_id = "prev_event_id"
  357. event = create_event(
  358. type="state", state_key="", name="event2", prev_events=[(prev_event_id, {})]
  359. )
  360. old_state = [
  361. create_event(type="test1", state_key="1"),
  362. create_event(type="test1", state_key="2"),
  363. create_event(type="test2", state_key=""),
  364. ]
  365. group_name = self.store.store_state_group(
  366. prev_event_id,
  367. event.room_id,
  368. None,
  369. None,
  370. {(e.type, e.state_key): e.event_id for e in old_state},
  371. )
  372. self.store.register_event_id_state_group(prev_event_id, group_name)
  373. context = yield self.state.compute_event_context(event)
  374. prev_state_ids = yield context.get_prev_state_ids(self.store)
  375. self.assertEqual(
  376. set([e.event_id for e in old_state]), set(prev_state_ids.values())
  377. )
  378. self.assertIsNotNone(context.state_group)
  379. @defer.inlineCallbacks
  380. def test_resolve_message_conflict(self):
  381. prev_event_id1 = "event_id1"
  382. prev_event_id2 = "event_id2"
  383. event = create_event(
  384. type="test_message",
  385. name="event3",
  386. prev_events=[(prev_event_id1, {}), (prev_event_id2, {})],
  387. )
  388. creation = create_event(type=EventTypes.Create, state_key="")
  389. old_state_1 = [
  390. creation,
  391. create_event(type="test1", state_key="1"),
  392. create_event(type="test1", state_key="2"),
  393. create_event(type="test2", state_key=""),
  394. ]
  395. old_state_2 = [
  396. creation,
  397. create_event(type="test1", state_key="1"),
  398. create_event(type="test3", state_key="2"),
  399. create_event(type="test4", state_key=""),
  400. ]
  401. self.store.register_events(old_state_1)
  402. self.store.register_events(old_state_2)
  403. context = yield self._get_context(
  404. event, prev_event_id1, old_state_1, prev_event_id2, old_state_2
  405. )
  406. current_state_ids = yield context.get_current_state_ids(self.store)
  407. self.assertEqual(len(current_state_ids), 6)
  408. self.assertIsNotNone(context.state_group)
  409. @defer.inlineCallbacks
  410. def test_resolve_state_conflict(self):
  411. prev_event_id1 = "event_id1"
  412. prev_event_id2 = "event_id2"
  413. event = create_event(
  414. type="test4",
  415. state_key="",
  416. name="event",
  417. prev_events=[(prev_event_id1, {}), (prev_event_id2, {})],
  418. )
  419. creation = create_event(type=EventTypes.Create, state_key="")
  420. old_state_1 = [
  421. creation,
  422. create_event(type="test1", state_key="1"),
  423. create_event(type="test1", state_key="2"),
  424. create_event(type="test2", state_key=""),
  425. ]
  426. old_state_2 = [
  427. creation,
  428. create_event(type="test1", state_key="1"),
  429. create_event(type="test3", state_key="2"),
  430. create_event(type="test4", state_key=""),
  431. ]
  432. store = StateGroupStore()
  433. store.register_events(old_state_1)
  434. store.register_events(old_state_2)
  435. self.store.get_events = store.get_events
  436. context = yield self._get_context(
  437. event, prev_event_id1, old_state_1, prev_event_id2, old_state_2
  438. )
  439. current_state_ids = yield context.get_current_state_ids(self.store)
  440. self.assertEqual(len(current_state_ids), 6)
  441. self.assertIsNotNone(context.state_group)
  442. @defer.inlineCallbacks
  443. def test_standard_depth_conflict(self):
  444. prev_event_id1 = "event_id1"
  445. prev_event_id2 = "event_id2"
  446. event = create_event(
  447. type="test4",
  448. name="event",
  449. prev_events=[(prev_event_id1, {}), (prev_event_id2, {})],
  450. )
  451. member_event = create_event(
  452. type=EventTypes.Member,
  453. state_key="@user_id:example.com",
  454. content={"membership": Membership.JOIN},
  455. )
  456. power_levels = create_event(
  457. type=EventTypes.PowerLevels,
  458. state_key="",
  459. content={"users": {"@foo:bar": "100", "@user_id:example.com": "100"}},
  460. )
  461. creation = create_event(
  462. type=EventTypes.Create, state_key="", content={"creator": "@foo:bar"}
  463. )
  464. old_state_1 = [
  465. creation,
  466. power_levels,
  467. member_event,
  468. create_event(type="test1", state_key="1", depth=1),
  469. ]
  470. old_state_2 = [
  471. creation,
  472. power_levels,
  473. member_event,
  474. create_event(type="test1", state_key="1", depth=2),
  475. ]
  476. store = StateGroupStore()
  477. store.register_events(old_state_1)
  478. store.register_events(old_state_2)
  479. self.store.get_events = store.get_events
  480. context = yield self._get_context(
  481. event, prev_event_id1, old_state_1, prev_event_id2, old_state_2
  482. )
  483. current_state_ids = yield context.get_current_state_ids(self.store)
  484. self.assertEqual(old_state_2[3].event_id, current_state_ids[("test1", "1")])
  485. # Reverse the depth to make sure we are actually using the depths
  486. # during state resolution.
  487. old_state_1 = [
  488. creation,
  489. power_levels,
  490. member_event,
  491. create_event(type="test1", state_key="1", depth=2),
  492. ]
  493. old_state_2 = [
  494. creation,
  495. power_levels,
  496. member_event,
  497. create_event(type="test1", state_key="1", depth=1),
  498. ]
  499. store.register_events(old_state_1)
  500. store.register_events(old_state_2)
  501. context = yield self._get_context(
  502. event, prev_event_id1, old_state_1, prev_event_id2, old_state_2
  503. )
  504. current_state_ids = yield context.get_current_state_ids(self.store)
  505. self.assertEqual(old_state_1[3].event_id, current_state_ids[("test1", "1")])
  506. def _get_context(
  507. self, event, prev_event_id_1, old_state_1, prev_event_id_2, old_state_2
  508. ):
  509. sg1 = self.store.store_state_group(
  510. prev_event_id_1,
  511. event.room_id,
  512. None,
  513. None,
  514. {(e.type, e.state_key): e.event_id for e in old_state_1},
  515. )
  516. self.store.register_event_id_state_group(prev_event_id_1, sg1)
  517. sg2 = self.store.store_state_group(
  518. prev_event_id_2,
  519. event.room_id,
  520. None,
  521. None,
  522. {(e.type, e.state_key): e.event_id for e in old_state_2},
  523. )
  524. self.store.register_event_id_state_group(prev_event_id_2, sg2)
  525. return self.state.compute_event_context(event)