test_state.py 20 KB

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