test_state.py 19 KB

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