test_state.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  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._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_set=[
  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_clock.return_value = MockClock()
  112. hs.get_auth.return_value = Auth(hs)
  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_branch_have_perms_conflict(self):
  268. userid1 = "@user_id:example.com"
  269. userid2 = "@user_id2:example.com"
  270. nodes = {
  271. "A1": DictObj(
  272. type=EventTypes.Create,
  273. state_key="",
  274. content={"creator": userid1},
  275. depth=1,
  276. ),
  277. "A2": DictObj(
  278. type=EventTypes.Member,
  279. state_key=userid1,
  280. content={"membership": Membership.JOIN},
  281. membership=Membership.JOIN,
  282. ),
  283. "A3": DictObj(
  284. type=EventTypes.Member,
  285. state_key=userid2,
  286. content={"membership": Membership.JOIN},
  287. membership=Membership.JOIN,
  288. ),
  289. "A4": DictObj(
  290. type=EventTypes.PowerLevels,
  291. state_key="",
  292. content={
  293. "events": {"m.room.name": 50},
  294. "users": {userid1: 100,
  295. userid2: 60},
  296. },
  297. ),
  298. "A5": DictObj(
  299. type=EventTypes.Name,
  300. state_key="",
  301. ),
  302. "B": DictObj(
  303. type=EventTypes.PowerLevels,
  304. state_key="",
  305. content={
  306. "events": {"m.room.name": 50},
  307. "users": {userid2: 30},
  308. },
  309. ),
  310. "C": DictObj(
  311. type=EventTypes.Name,
  312. state_key="",
  313. sender=userid2,
  314. ),
  315. "D": DictObj(
  316. type=EventTypes.Message,
  317. ),
  318. }
  319. edges = {
  320. "A2": ["A1"],
  321. "A3": ["A2"],
  322. "A4": ["A3"],
  323. "A5": ["A4"],
  324. "B": ["A5"],
  325. "C": ["A5"],
  326. "D": ["B", "C"]
  327. }
  328. self._add_depths(nodes, edges)
  329. graph = Graph(nodes, edges)
  330. store = StateGroupStore()
  331. self.store.get_state_groups.side_effect = store.get_state_groups
  332. context_store = {}
  333. for event in graph.walk():
  334. context = yield self.state.compute_event_context(event)
  335. store.store_state_groups(event, context)
  336. context_store[event.event_id] = context
  337. self.assertSetEqual(
  338. {"A1", "A2", "A3", "A5", "B"},
  339. {e.event_id for e in context_store["D"].current_state.values()}
  340. )
  341. def _add_depths(self, nodes, edges):
  342. def _get_depth(ev):
  343. node = nodes[ev]
  344. if 'depth' not in node:
  345. prevs = edges[ev]
  346. depth = max(_get_depth(prev) for prev in prevs) + 1
  347. node['depth'] = depth
  348. return node['depth']
  349. for n in nodes:
  350. _get_depth(n)
  351. @defer.inlineCallbacks
  352. def test_annotate_with_old_message(self):
  353. event = create_event(type="test_message", name="event")
  354. old_state = [
  355. create_event(type="test1", state_key="1"),
  356. create_event(type="test1", state_key="2"),
  357. create_event(type="test2", state_key=""),
  358. ]
  359. context = yield self.state.compute_event_context(
  360. event, old_state=old_state
  361. )
  362. for k, v in context.current_state.items():
  363. type, state_key = k
  364. self.assertEqual(type, v.type)
  365. self.assertEqual(state_key, v.state_key)
  366. self.assertEqual(
  367. set(old_state), set(context.current_state.values())
  368. )
  369. self.assertIsNone(context.state_group)
  370. @defer.inlineCallbacks
  371. def test_annotate_with_old_state(self):
  372. event = create_event(type="state", state_key="", name="event")
  373. old_state = [
  374. create_event(type="test1", state_key="1"),
  375. create_event(type="test1", state_key="2"),
  376. create_event(type="test2", state_key=""),
  377. ]
  378. context = yield self.state.compute_event_context(
  379. event, old_state=old_state
  380. )
  381. for k, v in context.current_state.items():
  382. type, state_key = k
  383. self.assertEqual(type, v.type)
  384. self.assertEqual(state_key, v.state_key)
  385. self.assertEqual(
  386. set(old_state),
  387. set(context.current_state.values())
  388. )
  389. self.assertIsNone(context.state_group)
  390. @defer.inlineCallbacks
  391. def test_trivial_annotate_message(self):
  392. event = create_event(type="test_message", name="event")
  393. old_state = [
  394. create_event(type="test1", state_key="1"),
  395. create_event(type="test1", state_key="2"),
  396. create_event(type="test2", state_key=""),
  397. ]
  398. group_name = "group_name_1"
  399. self.store.get_state_groups.return_value = {
  400. group_name: old_state,
  401. }
  402. context = yield self.state.compute_event_context(event)
  403. for k, v in context.current_state.items():
  404. type, state_key = k
  405. self.assertEqual(type, v.type)
  406. self.assertEqual(state_key, v.state_key)
  407. self.assertEqual(
  408. set([e.event_id for e in old_state]),
  409. set([e.event_id for e in context.current_state.values()])
  410. )
  411. self.assertEqual(group_name, context.state_group)
  412. @defer.inlineCallbacks
  413. def test_trivial_annotate_state(self):
  414. event = create_event(type="state", state_key="", name="event")
  415. old_state = [
  416. create_event(type="test1", state_key="1"),
  417. create_event(type="test1", state_key="2"),
  418. create_event(type="test2", state_key=""),
  419. ]
  420. group_name = "group_name_1"
  421. self.store.get_state_groups.return_value = {
  422. group_name: old_state,
  423. }
  424. context = yield self.state.compute_event_context(event)
  425. for k, v in context.current_state.items():
  426. type, state_key = k
  427. self.assertEqual(type, v.type)
  428. self.assertEqual(state_key, v.state_key)
  429. self.assertEqual(
  430. set([e.event_id for e in old_state]),
  431. set([e.event_id for e in context.current_state.values()])
  432. )
  433. self.assertIsNone(context.state_group)
  434. @defer.inlineCallbacks
  435. def test_resolve_message_conflict(self):
  436. event = create_event(type="test_message", name="event")
  437. creation = create_event(
  438. type=EventTypes.Create, state_key=""
  439. )
  440. old_state_1 = [
  441. creation,
  442. create_event(type="test1", state_key="1"),
  443. create_event(type="test1", state_key="2"),
  444. create_event(type="test2", state_key=""),
  445. ]
  446. old_state_2 = [
  447. creation,
  448. create_event(type="test1", state_key="1"),
  449. create_event(type="test3", state_key="2"),
  450. create_event(type="test4", state_key=""),
  451. ]
  452. context = yield self._get_context(event, old_state_1, old_state_2)
  453. self.assertEqual(len(context.current_state), 6)
  454. self.assertIsNone(context.state_group)
  455. @defer.inlineCallbacks
  456. def test_resolve_state_conflict(self):
  457. event = create_event(type="test4", state_key="", name="event")
  458. creation = create_event(
  459. type=EventTypes.Create, state_key=""
  460. )
  461. old_state_1 = [
  462. creation,
  463. create_event(type="test1", state_key="1"),
  464. create_event(type="test1", state_key="2"),
  465. create_event(type="test2", state_key=""),
  466. ]
  467. old_state_2 = [
  468. creation,
  469. create_event(type="test1", state_key="1"),
  470. create_event(type="test3", state_key="2"),
  471. create_event(type="test4", state_key=""),
  472. ]
  473. context = yield self._get_context(event, old_state_1, old_state_2)
  474. self.assertEqual(len(context.current_state), 6)
  475. self.assertIsNone(context.state_group)
  476. @defer.inlineCallbacks
  477. def test_standard_depth_conflict(self):
  478. event = create_event(type="test4", name="event")
  479. member_event = create_event(
  480. type=EventTypes.Member,
  481. state_key="@user_id:example.com",
  482. content={
  483. "membership": Membership.JOIN,
  484. }
  485. )
  486. creation = create_event(
  487. type=EventTypes.Create, state_key="",
  488. content={"creator": "@foo:bar"}
  489. )
  490. old_state_1 = [
  491. creation,
  492. member_event,
  493. create_event(type="test1", state_key="1", depth=1),
  494. ]
  495. old_state_2 = [
  496. creation,
  497. member_event,
  498. create_event(type="test1", state_key="1", depth=2),
  499. ]
  500. context = yield self._get_context(event, old_state_1, old_state_2)
  501. self.assertEqual(old_state_2[2], context.current_state[("test1", "1")])
  502. # Reverse the depth to make sure we are actually using the depths
  503. # during state resolution.
  504. old_state_1 = [
  505. creation,
  506. member_event,
  507. create_event(type="test1", state_key="1", depth=2),
  508. ]
  509. old_state_2 = [
  510. creation,
  511. member_event,
  512. create_event(type="test1", state_key="1", depth=1),
  513. ]
  514. context = yield self._get_context(event, old_state_1, old_state_2)
  515. self.assertEqual(old_state_1[2], context.current_state[("test1", "1")])
  516. def _get_context(self, event, old_state_1, old_state_2):
  517. group_name_1 = "group_name_1"
  518. group_name_2 = "group_name_2"
  519. self.store.get_state_groups.return_value = {
  520. group_name_1: old_state_1,
  521. group_name_2: old_state_2,
  522. }
  523. return self.state.compute_event_context(event)