test_state.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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(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. prev_state_ids = yield context_store["D"].get_prev_state_ids(self.store)
  162. self.assertEqual(2, len(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. self.store.register_events(graph.walk())
  203. context_store = {}
  204. for event in graph.walk():
  205. context = yield self.state.compute_event_context(event)
  206. self.store.register_event_context(event, context)
  207. context_store[event.event_id] = context
  208. prev_state_ids = yield context_store["D"].get_prev_state_ids(self.store)
  209. self.assertSetEqual(
  210. {"START", "A", "C"},
  211. {e_id for e_id in prev_state_ids.values()}
  212. )
  213. @defer.inlineCallbacks
  214. def test_branch_have_banned_conflict(self):
  215. graph = Graph(
  216. nodes={
  217. "START": DictObj(
  218. type=EventTypes.Create,
  219. state_key="",
  220. content={"creator": "@user_id:example.com"},
  221. depth=1,
  222. ),
  223. "A": DictObj(
  224. type=EventTypes.Member,
  225. state_key="@user_id:example.com",
  226. content={"membership": Membership.JOIN},
  227. membership=Membership.JOIN,
  228. depth=2,
  229. ),
  230. "B": DictObj(
  231. type=EventTypes.Name,
  232. state_key="",
  233. depth=3,
  234. ),
  235. "C": DictObj(
  236. type=EventTypes.Member,
  237. state_key="@user_id_2:example.com",
  238. content={"membership": Membership.BAN},
  239. membership=Membership.BAN,
  240. depth=4,
  241. ),
  242. "D": DictObj(
  243. type=EventTypes.Name,
  244. state_key="",
  245. depth=4,
  246. sender="@user_id_2:example.com",
  247. ),
  248. "E": DictObj(
  249. type=EventTypes.Message,
  250. depth=5,
  251. ),
  252. },
  253. edges={
  254. "A": ["START"],
  255. "B": ["A"],
  256. "C": ["B"],
  257. "D": ["B"],
  258. "E": ["C", "D"]
  259. }
  260. )
  261. self.store.register_events(graph.walk())
  262. context_store = {}
  263. for event in graph.walk():
  264. context = yield self.state.compute_event_context(event)
  265. self.store.register_event_context(event, context)
  266. context_store[event.event_id] = context
  267. prev_state_ids = yield context_store["E"].get_prev_state_ids(self.store)
  268. self.assertSetEqual(
  269. {"START", "A", "B", "C"},
  270. {e for e in prev_state_ids.values()}
  271. )
  272. @defer.inlineCallbacks
  273. def test_branch_have_perms_conflict(self):
  274. userid1 = "@user_id:example.com"
  275. userid2 = "@user_id2:example.com"
  276. nodes = {
  277. "A1": DictObj(
  278. type=EventTypes.Create,
  279. state_key="",
  280. content={"creator": userid1},
  281. depth=1,
  282. ),
  283. "A2": DictObj(
  284. type=EventTypes.Member,
  285. state_key=userid1,
  286. content={"membership": Membership.JOIN},
  287. membership=Membership.JOIN,
  288. ),
  289. "A3": DictObj(
  290. type=EventTypes.Member,
  291. state_key=userid2,
  292. content={"membership": Membership.JOIN},
  293. membership=Membership.JOIN,
  294. ),
  295. "A4": DictObj(
  296. type=EventTypes.PowerLevels,
  297. state_key="",
  298. content={
  299. "events": {"m.room.name": 50},
  300. "users": {userid1: 100,
  301. userid2: 60},
  302. },
  303. ),
  304. "A5": DictObj(
  305. type=EventTypes.Name,
  306. state_key="",
  307. ),
  308. "B": DictObj(
  309. type=EventTypes.PowerLevels,
  310. state_key="",
  311. content={
  312. "events": {"m.room.name": 50},
  313. "users": {userid2: 30},
  314. },
  315. ),
  316. "C": DictObj(
  317. type=EventTypes.Name,
  318. state_key="",
  319. sender=userid2,
  320. ),
  321. "D": DictObj(
  322. type=EventTypes.Message,
  323. ),
  324. }
  325. edges = {
  326. "A2": ["A1"],
  327. "A3": ["A2"],
  328. "A4": ["A3"],
  329. "A5": ["A4"],
  330. "B": ["A5"],
  331. "C": ["A5"],
  332. "D": ["B", "C"]
  333. }
  334. self._add_depths(nodes, edges)
  335. graph = Graph(nodes, edges)
  336. self.store.register_events(graph.walk())
  337. context_store = {}
  338. for event in graph.walk():
  339. context = yield self.state.compute_event_context(event)
  340. self.store.register_event_context(event, context)
  341. context_store[event.event_id] = context
  342. prev_state_ids = yield context_store["D"].get_prev_state_ids(self.store)
  343. self.assertSetEqual(
  344. {"A1", "A2", "A3", "A5", "B"},
  345. {e for e in prev_state_ids.values()}
  346. )
  347. def _add_depths(self, nodes, edges):
  348. def _get_depth(ev):
  349. node = nodes[ev]
  350. if 'depth' not in node:
  351. prevs = edges[ev]
  352. depth = max(_get_depth(prev) for prev in prevs) + 1
  353. node['depth'] = depth
  354. return node['depth']
  355. for n in nodes:
  356. _get_depth(n)
  357. @defer.inlineCallbacks
  358. def test_annotate_with_old_message(self):
  359. event = create_event(type="test_message", name="event")
  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. context = yield self.state.compute_event_context(
  366. event, old_state=old_state
  367. )
  368. current_state_ids = yield context.get_current_state_ids(self.store)
  369. self.assertEqual(
  370. set(e.event_id for e in old_state), set(current_state_ids.values())
  371. )
  372. self.assertIsNotNone(context.state_group)
  373. @defer.inlineCallbacks
  374. def test_annotate_with_old_state(self):
  375. event = create_event(type="state", state_key="", name="event")
  376. old_state = [
  377. create_event(type="test1", state_key="1"),
  378. create_event(type="test1", state_key="2"),
  379. create_event(type="test2", state_key=""),
  380. ]
  381. context = yield self.state.compute_event_context(
  382. event, old_state=old_state
  383. )
  384. prev_state_ids = yield context.get_prev_state_ids(self.store)
  385. self.assertEqual(
  386. set(e.event_id for e in old_state), set(prev_state_ids.values())
  387. )
  388. @defer.inlineCallbacks
  389. def test_trivial_annotate_message(self):
  390. prev_event_id = "prev_event_id"
  391. event = create_event(
  392. type="test_message", name="event2",
  393. prev_events=[(prev_event_id, {})],
  394. )
  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 = self.store.store_state_group(
  401. prev_event_id, event.room_id, None, None,
  402. {(e.type, e.state_key): e.event_id for e in old_state},
  403. )
  404. self.store.register_event_id_state_group(prev_event_id, group_name)
  405. context = yield self.state.compute_event_context(event)
  406. current_state_ids = yield context.get_current_state_ids(self.store)
  407. self.assertEqual(
  408. set([e.event_id for e in old_state]),
  409. set(current_state_ids.values())
  410. )
  411. self.assertEqual(group_name, context.state_group)
  412. @defer.inlineCallbacks
  413. def test_trivial_annotate_state(self):
  414. prev_event_id = "prev_event_id"
  415. event = create_event(
  416. type="state", state_key="", name="event2",
  417. prev_events=[(prev_event_id, {})],
  418. )
  419. old_state = [
  420. create_event(type="test1", state_key="1"),
  421. create_event(type="test1", state_key="2"),
  422. create_event(type="test2", state_key=""),
  423. ]
  424. group_name = self.store.store_state_group(
  425. prev_event_id, event.room_id, None, None,
  426. {(e.type, e.state_key): e.event_id for e in old_state},
  427. )
  428. self.store.register_event_id_state_group(prev_event_id, group_name)
  429. context = yield self.state.compute_event_context(event)
  430. prev_state_ids = yield context.get_prev_state_ids(self.store)
  431. self.assertEqual(
  432. set([e.event_id for e in old_state]),
  433. set(prev_state_ids.values())
  434. )
  435. self.assertIsNotNone(context.state_group)
  436. @defer.inlineCallbacks
  437. def test_resolve_message_conflict(self):
  438. prev_event_id1 = "event_id1"
  439. prev_event_id2 = "event_id2"
  440. event = create_event(
  441. type="test_message", name="event3",
  442. prev_events=[(prev_event_id1, {}), (prev_event_id2, {})],
  443. )
  444. creation = create_event(
  445. type=EventTypes.Create, state_key=""
  446. )
  447. old_state_1 = [
  448. creation,
  449. create_event(type="test1", state_key="1"),
  450. create_event(type="test1", state_key="2"),
  451. create_event(type="test2", state_key=""),
  452. ]
  453. old_state_2 = [
  454. creation,
  455. create_event(type="test1", state_key="1"),
  456. create_event(type="test3", state_key="2"),
  457. create_event(type="test4", state_key=""),
  458. ]
  459. self.store.register_events(old_state_1)
  460. self.store.register_events(old_state_2)
  461. context = yield self._get_context(
  462. event, prev_event_id1, old_state_1, prev_event_id2, old_state_2,
  463. )
  464. current_state_ids = yield context.get_current_state_ids(self.store)
  465. self.assertEqual(len(current_state_ids), 6)
  466. self.assertIsNotNone(context.state_group)
  467. @defer.inlineCallbacks
  468. def test_resolve_state_conflict(self):
  469. prev_event_id1 = "event_id1"
  470. prev_event_id2 = "event_id2"
  471. event = create_event(
  472. type="test4", state_key="", name="event",
  473. prev_events=[(prev_event_id1, {}), (prev_event_id2, {})],
  474. )
  475. creation = create_event(
  476. type=EventTypes.Create, state_key=""
  477. )
  478. old_state_1 = [
  479. creation,
  480. create_event(type="test1", state_key="1"),
  481. create_event(type="test1", state_key="2"),
  482. create_event(type="test2", state_key=""),
  483. ]
  484. old_state_2 = [
  485. creation,
  486. create_event(type="test1", state_key="1"),
  487. create_event(type="test3", state_key="2"),
  488. create_event(type="test4", state_key=""),
  489. ]
  490. store = StateGroupStore()
  491. store.register_events(old_state_1)
  492. store.register_events(old_state_2)
  493. self.store.get_events = store.get_events
  494. context = yield self._get_context(
  495. event, prev_event_id1, old_state_1, prev_event_id2, old_state_2,
  496. )
  497. current_state_ids = yield context.get_current_state_ids(self.store)
  498. self.assertEqual(len(current_state_ids), 6)
  499. self.assertIsNotNone(context.state_group)
  500. @defer.inlineCallbacks
  501. def test_standard_depth_conflict(self):
  502. prev_event_id1 = "event_id1"
  503. prev_event_id2 = "event_id2"
  504. event = create_event(
  505. type="test4", name="event",
  506. prev_events=[(prev_event_id1, {}), (prev_event_id2, {})],
  507. )
  508. member_event = create_event(
  509. type=EventTypes.Member,
  510. state_key="@user_id:example.com",
  511. content={
  512. "membership": Membership.JOIN,
  513. }
  514. )
  515. power_levels = create_event(
  516. type=EventTypes.PowerLevels, state_key="",
  517. content={"users": {
  518. "@foo:bar": "100",
  519. "@user_id:example.com": "100",
  520. }}
  521. )
  522. creation = create_event(
  523. type=EventTypes.Create, state_key="",
  524. content={"creator": "@foo:bar"}
  525. )
  526. old_state_1 = [
  527. creation,
  528. power_levels,
  529. member_event,
  530. create_event(type="test1", state_key="1", depth=1),
  531. ]
  532. old_state_2 = [
  533. creation,
  534. power_levels,
  535. member_event,
  536. create_event(type="test1", state_key="1", depth=2),
  537. ]
  538. store = StateGroupStore()
  539. store.register_events(old_state_1)
  540. store.register_events(old_state_2)
  541. self.store.get_events = store.get_events
  542. context = yield self._get_context(
  543. event, prev_event_id1, old_state_1, prev_event_id2, old_state_2,
  544. )
  545. current_state_ids = yield context.get_current_state_ids(self.store)
  546. self.assertEqual(
  547. old_state_2[3].event_id, current_state_ids[("test1", "1")]
  548. )
  549. # Reverse the depth to make sure we are actually using the depths
  550. # during state resolution.
  551. old_state_1 = [
  552. creation,
  553. power_levels,
  554. member_event,
  555. create_event(type="test1", state_key="1", depth=2),
  556. ]
  557. old_state_2 = [
  558. creation,
  559. power_levels,
  560. member_event,
  561. create_event(type="test1", state_key="1", depth=1),
  562. ]
  563. store.register_events(old_state_1)
  564. store.register_events(old_state_2)
  565. context = yield self._get_context(
  566. event, prev_event_id1, old_state_1, prev_event_id2, old_state_2,
  567. )
  568. current_state_ids = yield context.get_current_state_ids(self.store)
  569. self.assertEqual(
  570. old_state_1[3].event_id, current_state_ids[("test1", "1")]
  571. )
  572. def _get_context(self, event, prev_event_id_1, old_state_1, prev_event_id_2,
  573. old_state_2):
  574. sg1 = self.store.store_state_group(
  575. prev_event_id_1, event.room_id, None, None,
  576. {(e.type, e.state_key): e.event_id for e in old_state_1},
  577. )
  578. self.store.register_event_id_state_group(prev_event_id_1, sg1)
  579. sg2 = self.store.store_state_group(
  580. prev_event_id_2, event.room_id, None, None,
  581. {(e.type, e.state_key): e.event_id for e in old_state_2},
  582. )
  583. self.store.register_event_id_state_group(prev_event_id_2, sg2)
  584. return self.state.compute_event_context(event)