stream.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  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. """ This module is responsible for getting events from the DB for pagination
  16. and event streaming.
  17. The order it returns events in depend on whether we are streaming forwards or
  18. are paginating backwards. We do this because we want to handle out of order
  19. messages nicely, while still returning them in the correct order when we
  20. paginate bacwards.
  21. This is implemented by keeping two ordering columns: stream_ordering and
  22. topological_ordering. Stream ordering is basically insertion/received order
  23. (except for events from backfill requests). The topological_ordering is a
  24. weak ordering of events based on the pdu graph.
  25. This means that we have to have two different types of tokens, depending on
  26. what sort order was used:
  27. - stream tokens are of the form: "s%d", which maps directly to the column
  28. - topological tokems: "t%d-%d", where the integers map to the topological
  29. and stream ordering columns respectively.
  30. """
  31. from twisted.internet import defer
  32. from ._base import SQLBaseStore
  33. from synapse.util.caches.descriptors import cached
  34. from synapse.api.constants import EventTypes
  35. from synapse.types import RoomStreamToken
  36. from synapse.util.logcontext import preserve_fn, preserve_context_over_deferred
  37. from synapse.storage.engines import PostgresEngine, Sqlite3Engine
  38. import logging
  39. logger = logging.getLogger(__name__)
  40. MAX_STREAM_SIZE = 1000
  41. _STREAM_TOKEN = "stream"
  42. _TOPOLOGICAL_TOKEN = "topological"
  43. def lower_bound(token, engine, inclusive=False):
  44. inclusive = "=" if inclusive else ""
  45. if token.topological is None:
  46. return "(%d <%s %s)" % (token.stream, inclusive, "stream_ordering")
  47. else:
  48. if isinstance(engine, PostgresEngine):
  49. # Postgres doesn't optimise ``(x < a) OR (x=a AND y<b)`` as well
  50. # as it optimises ``(x,y) < (a,b)`` on multicolumn indexes. So we
  51. # use the later form when running against postgres.
  52. return "((%d,%d) <%s (%s,%s))" % (
  53. token.topological, token.stream, inclusive,
  54. "topological_ordering", "stream_ordering",
  55. )
  56. return "(%d < %s OR (%d = %s AND %d <%s %s))" % (
  57. token.topological, "topological_ordering",
  58. token.topological, "topological_ordering",
  59. token.stream, inclusive, "stream_ordering",
  60. )
  61. def upper_bound(token, engine, inclusive=True):
  62. inclusive = "=" if inclusive else ""
  63. if token.topological is None:
  64. return "(%d >%s %s)" % (token.stream, inclusive, "stream_ordering")
  65. else:
  66. if isinstance(engine, PostgresEngine):
  67. # Postgres doesn't optimise ``(x > a) OR (x=a AND y>b)`` as well
  68. # as it optimises ``(x,y) > (a,b)`` on multicolumn indexes. So we
  69. # use the later form when running against postgres.
  70. return "((%d,%d) >%s (%s,%s))" % (
  71. token.topological, token.stream, inclusive,
  72. "topological_ordering", "stream_ordering",
  73. )
  74. return "(%d > %s OR (%d = %s AND %d >%s %s))" % (
  75. token.topological, "topological_ordering",
  76. token.topological, "topological_ordering",
  77. token.stream, inclusive, "stream_ordering",
  78. )
  79. def filter_to_clause(event_filter):
  80. # NB: This may create SQL clauses that don't optimise well (and we don't
  81. # have indices on all possible clauses). E.g. it may create
  82. # "room_id == X AND room_id != X", which postgres doesn't optimise.
  83. if not event_filter:
  84. return "", []
  85. clauses = []
  86. args = []
  87. if event_filter.types:
  88. clauses.append(
  89. "(%s)" % " OR ".join("type = ?" for _ in event_filter.types)
  90. )
  91. args.extend(event_filter.types)
  92. for typ in event_filter.not_types:
  93. clauses.append("type != ?")
  94. args.append(typ)
  95. if event_filter.senders:
  96. clauses.append(
  97. "(%s)" % " OR ".join("sender = ?" for _ in event_filter.senders)
  98. )
  99. args.extend(event_filter.senders)
  100. for sender in event_filter.not_senders:
  101. clauses.append("sender != ?")
  102. args.append(sender)
  103. if event_filter.rooms:
  104. clauses.append(
  105. "(%s)" % " OR ".join("room_id = ?" for _ in event_filter.rooms)
  106. )
  107. args.extend(event_filter.rooms)
  108. for room_id in event_filter.not_rooms:
  109. clauses.append("room_id != ?")
  110. args.append(room_id)
  111. if event_filter.contains_url:
  112. clauses.append("contains_url = ?")
  113. args.append(event_filter.contains_url)
  114. return " AND ".join(clauses), args
  115. class StreamStore(SQLBaseStore):
  116. @defer.inlineCallbacks
  117. def get_appservice_room_stream(self, service, from_key, to_key, limit=0):
  118. # NB this lives here instead of appservice.py so we can reuse the
  119. # 'private' StreamToken class in this file.
  120. if limit:
  121. limit = max(limit, MAX_STREAM_SIZE)
  122. else:
  123. limit = MAX_STREAM_SIZE
  124. # From and to keys should be integers from ordering.
  125. from_id = RoomStreamToken.parse_stream_token(from_key)
  126. to_id = RoomStreamToken.parse_stream_token(to_key)
  127. if from_key == to_key:
  128. defer.returnValue(([], to_key))
  129. return
  130. # select all the events between from/to with a sensible limit
  131. sql = (
  132. "SELECT e.event_id, e.room_id, e.type, s.state_key, "
  133. "e.stream_ordering FROM events AS e "
  134. "LEFT JOIN state_events as s ON "
  135. "e.event_id = s.event_id "
  136. "WHERE e.stream_ordering > ? AND e.stream_ordering <= ? "
  137. "ORDER BY stream_ordering ASC LIMIT %(limit)d "
  138. ) % {
  139. "limit": limit
  140. }
  141. def f(txn):
  142. # pull out all the events between the tokens
  143. txn.execute(sql, (from_id.stream, to_id.stream,))
  144. rows = self.cursor_to_dict(txn)
  145. # Logic:
  146. # - We want ALL events which match the AS room_id regex
  147. # - We want ALL events which match the rooms represented by the AS
  148. # room_alias regex
  149. # - We want ALL events for rooms that AS users have joined.
  150. # This is currently supported via get_app_service_rooms (which is
  151. # used for the Notifier listener rooms). We can't reasonably make a
  152. # SQL query for these room IDs, so we'll pull all the events between
  153. # from/to and filter in python.
  154. rooms_for_as = self._get_app_service_rooms_txn(txn, service)
  155. room_ids_for_as = [r.room_id for r in rooms_for_as]
  156. def app_service_interested(row):
  157. if row["room_id"] in room_ids_for_as:
  158. return True
  159. if row["type"] == EventTypes.Member:
  160. if service.is_interested_in_user(row.get("state_key")):
  161. return True
  162. return False
  163. return [r for r in rows if app_service_interested(r)]
  164. rows = yield self.runInteraction("get_appservice_room_stream", f)
  165. ret = yield self._get_events(
  166. [r["event_id"] for r in rows],
  167. get_prev_content=True
  168. )
  169. self._set_before_and_after(ret, rows, topo_order=from_id is None)
  170. if rows:
  171. key = "s%d" % max(r["stream_ordering"] for r in rows)
  172. else:
  173. # Assume we didn't get anything because there was nothing to
  174. # get.
  175. key = to_key
  176. defer.returnValue((ret, key))
  177. @defer.inlineCallbacks
  178. def get_room_events_stream_for_rooms(self, room_ids, from_key, to_key, limit=0,
  179. order='DESC'):
  180. from_id = RoomStreamToken.parse_stream_token(from_key).stream
  181. room_ids = yield self._events_stream_cache.get_entities_changed(
  182. room_ids, from_id
  183. )
  184. if not room_ids:
  185. defer.returnValue({})
  186. results = {}
  187. room_ids = list(room_ids)
  188. for rm_ids in (room_ids[i:i + 20] for i in xrange(0, len(room_ids), 20)):
  189. res = yield preserve_context_over_deferred(defer.gatherResults([
  190. preserve_fn(self.get_room_events_stream_for_room)(
  191. room_id, from_key, to_key, limit, order=order,
  192. )
  193. for room_id in rm_ids
  194. ]))
  195. results.update(dict(zip(rm_ids, res)))
  196. defer.returnValue(results)
  197. def get_rooms_that_changed(self, room_ids, from_key):
  198. """Given a list of rooms and a token, return rooms where there may have
  199. been changes.
  200. Args:
  201. room_ids (list)
  202. from_key (str): The room_key portion of a StreamToken
  203. """
  204. from_key = RoomStreamToken.parse_stream_token(from_key).stream
  205. return set(
  206. room_id for room_id in room_ids
  207. if self._events_stream_cache.has_entity_changed(room_id, from_key)
  208. )
  209. @defer.inlineCallbacks
  210. def get_room_events_stream_for_room(self, room_id, from_key, to_key, limit=0,
  211. order='DESC'):
  212. # Note: If from_key is None then we return in topological order. This
  213. # is because in that case we're using this as a "get the last few messages
  214. # in a room" function, rather than "get new messages since last sync"
  215. if from_key is not None:
  216. from_id = RoomStreamToken.parse_stream_token(from_key).stream
  217. else:
  218. from_id = None
  219. to_id = RoomStreamToken.parse_stream_token(to_key).stream
  220. if from_key == to_key:
  221. defer.returnValue(([], from_key))
  222. if from_id:
  223. has_changed = yield self._events_stream_cache.has_entity_changed(
  224. room_id, from_id
  225. )
  226. if not has_changed:
  227. defer.returnValue(([], from_key))
  228. def f(txn):
  229. if from_id is not None:
  230. sql = (
  231. "SELECT event_id, stream_ordering FROM events WHERE"
  232. " room_id = ?"
  233. " AND not outlier"
  234. " AND stream_ordering > ? AND stream_ordering <= ?"
  235. " ORDER BY stream_ordering %s LIMIT ?"
  236. ) % (order,)
  237. txn.execute(sql, (room_id, from_id, to_id, limit))
  238. else:
  239. sql = (
  240. "SELECT event_id, stream_ordering FROM events WHERE"
  241. " room_id = ?"
  242. " AND not outlier"
  243. " AND stream_ordering <= ?"
  244. " ORDER BY topological_ordering %s, stream_ordering %s LIMIT ?"
  245. ) % (order, order,)
  246. txn.execute(sql, (room_id, to_id, limit))
  247. rows = self.cursor_to_dict(txn)
  248. return rows
  249. rows = yield self.runInteraction("get_room_events_stream_for_room", f)
  250. ret = yield self._get_events(
  251. [r["event_id"] for r in rows],
  252. get_prev_content=True
  253. )
  254. self._set_before_and_after(ret, rows, topo_order=from_id is None)
  255. if order.lower() == "desc":
  256. ret.reverse()
  257. if rows:
  258. key = "s%d" % min(r["stream_ordering"] for r in rows)
  259. else:
  260. # Assume we didn't get anything because there was nothing to
  261. # get.
  262. key = from_key
  263. defer.returnValue((ret, key))
  264. @defer.inlineCallbacks
  265. def get_membership_changes_for_user(self, user_id, from_key, to_key):
  266. if from_key is not None:
  267. from_id = RoomStreamToken.parse_stream_token(from_key).stream
  268. else:
  269. from_id = None
  270. to_id = RoomStreamToken.parse_stream_token(to_key).stream
  271. if from_key == to_key:
  272. defer.returnValue([])
  273. if from_id:
  274. has_changed = self._membership_stream_cache.has_entity_changed(
  275. user_id, int(from_id)
  276. )
  277. if not has_changed:
  278. defer.returnValue([])
  279. def f(txn):
  280. if from_id is not None:
  281. sql = (
  282. "SELECT m.event_id, stream_ordering FROM events AS e,"
  283. " room_memberships AS m"
  284. " WHERE e.event_id = m.event_id"
  285. " AND m.user_id = ?"
  286. " AND e.stream_ordering > ? AND e.stream_ordering <= ?"
  287. " ORDER BY e.stream_ordering ASC"
  288. )
  289. txn.execute(sql, (user_id, from_id, to_id,))
  290. else:
  291. sql = (
  292. "SELECT m.event_id, stream_ordering FROM events AS e,"
  293. " room_memberships AS m"
  294. " WHERE e.event_id = m.event_id"
  295. " AND m.user_id = ?"
  296. " AND stream_ordering <= ?"
  297. " ORDER BY stream_ordering ASC"
  298. )
  299. txn.execute(sql, (user_id, to_id,))
  300. rows = self.cursor_to_dict(txn)
  301. return rows
  302. rows = yield self.runInteraction("get_membership_changes_for_user", f)
  303. ret = yield self._get_events(
  304. [r["event_id"] for r in rows],
  305. get_prev_content=True
  306. )
  307. self._set_before_and_after(ret, rows, topo_order=False)
  308. defer.returnValue(ret)
  309. @defer.inlineCallbacks
  310. def paginate_room_events(self, room_id, from_key, to_key=None,
  311. direction='b', limit=-1, event_filter=None):
  312. # Tokens really represent positions between elements, but we use
  313. # the convention of pointing to the event before the gap. Hence
  314. # we have a bit of asymmetry when it comes to equalities.
  315. args = [False, room_id]
  316. if direction == 'b':
  317. order = "DESC"
  318. bounds = upper_bound(
  319. RoomStreamToken.parse(from_key), self.database_engine
  320. )
  321. if to_key:
  322. bounds = "%s AND %s" % (bounds, lower_bound(
  323. RoomStreamToken.parse(to_key), self.database_engine
  324. ))
  325. else:
  326. order = "ASC"
  327. bounds = lower_bound(
  328. RoomStreamToken.parse(from_key), self.database_engine
  329. )
  330. if to_key:
  331. bounds = "%s AND %s" % (bounds, upper_bound(
  332. RoomStreamToken.parse(to_key), self.database_engine
  333. ))
  334. filter_clause, filter_args = filter_to_clause(event_filter)
  335. if filter_clause:
  336. bounds += " AND " + filter_clause
  337. args.extend(filter_args)
  338. if int(limit) > 0:
  339. args.append(int(limit))
  340. limit_str = " LIMIT ?"
  341. else:
  342. limit_str = ""
  343. sql = (
  344. "SELECT * FROM events"
  345. " WHERE outlier = ? AND room_id = ? AND %(bounds)s"
  346. " ORDER BY topological_ordering %(order)s,"
  347. " stream_ordering %(order)s %(limit)s"
  348. ) % {
  349. "bounds": bounds,
  350. "order": order,
  351. "limit": limit_str
  352. }
  353. def f(txn):
  354. txn.execute(sql, args)
  355. rows = self.cursor_to_dict(txn)
  356. if rows:
  357. topo = rows[-1]["topological_ordering"]
  358. toke = rows[-1]["stream_ordering"]
  359. if direction == 'b':
  360. # Tokens are positions between events.
  361. # This token points *after* the last event in the chunk.
  362. # We need it to point to the event before it in the chunk
  363. # when we are going backwards so we subtract one from the
  364. # stream part.
  365. toke -= 1
  366. next_token = str(RoomStreamToken(topo, toke))
  367. else:
  368. # TODO (erikj): We should work out what to do here instead.
  369. next_token = to_key if to_key else from_key
  370. return rows, next_token,
  371. rows, token = yield self.runInteraction("paginate_room_events", f)
  372. events = yield self._get_events(
  373. [r["event_id"] for r in rows],
  374. get_prev_content=True
  375. )
  376. self._set_before_and_after(events, rows)
  377. defer.returnValue((events, token))
  378. @defer.inlineCallbacks
  379. def get_recent_events_for_room(self, room_id, limit, end_token, from_token=None):
  380. rows, token = yield self.get_recent_event_ids_for_room(
  381. room_id, limit, end_token, from_token
  382. )
  383. logger.debug("stream before")
  384. events = yield self._get_events(
  385. [r["event_id"] for r in rows],
  386. get_prev_content=True
  387. )
  388. logger.debug("stream after")
  389. self._set_before_and_after(events, rows)
  390. defer.returnValue((events, token))
  391. @cached(num_args=4)
  392. def get_recent_event_ids_for_room(self, room_id, limit, end_token, from_token=None):
  393. end_token = RoomStreamToken.parse_stream_token(end_token)
  394. if from_token is None:
  395. sql = (
  396. "SELECT stream_ordering, topological_ordering, event_id"
  397. " FROM events"
  398. " WHERE room_id = ? AND stream_ordering <= ? AND outlier = ?"
  399. " ORDER BY topological_ordering DESC, stream_ordering DESC"
  400. " LIMIT ?"
  401. )
  402. else:
  403. from_token = RoomStreamToken.parse_stream_token(from_token)
  404. sql = (
  405. "SELECT stream_ordering, topological_ordering, event_id"
  406. " FROM events"
  407. " WHERE room_id = ? AND stream_ordering > ?"
  408. " AND stream_ordering <= ? AND outlier = ?"
  409. " ORDER BY topological_ordering DESC, stream_ordering DESC"
  410. " LIMIT ?"
  411. )
  412. def get_recent_events_for_room_txn(txn):
  413. if from_token is None:
  414. txn.execute(sql, (room_id, end_token.stream, False, limit,))
  415. else:
  416. txn.execute(sql, (
  417. room_id, from_token.stream, end_token.stream, False, limit
  418. ))
  419. rows = self.cursor_to_dict(txn)
  420. rows.reverse() # As we selected with reverse ordering
  421. if rows:
  422. # Tokens are positions between events.
  423. # This token points *after* the last event in the chunk.
  424. # We need it to point to the event before it in the chunk
  425. # since we are going backwards so we subtract one from the
  426. # stream part.
  427. topo = rows[0]["topological_ordering"]
  428. toke = rows[0]["stream_ordering"] - 1
  429. start_token = str(RoomStreamToken(topo, toke))
  430. token = (start_token, str(end_token))
  431. else:
  432. token = (str(end_token), str(end_token))
  433. return rows, token
  434. return self.runInteraction(
  435. "get_recent_events_for_room", get_recent_events_for_room_txn
  436. )
  437. @defer.inlineCallbacks
  438. def get_room_events_max_id(self, room_id=None):
  439. """Returns the current token for rooms stream.
  440. By default, it returns the current global stream token. Specifying a
  441. `room_id` causes it to return the current room specific topological
  442. token.
  443. """
  444. token = yield self._stream_id_gen.get_current_token()
  445. if room_id is None:
  446. defer.returnValue("s%d" % (token,))
  447. else:
  448. topo = yield self.runInteraction(
  449. "_get_max_topological_txn", self._get_max_topological_txn,
  450. room_id,
  451. )
  452. defer.returnValue("t%d-%d" % (topo, token))
  453. def get_room_max_stream_ordering(self):
  454. return self._stream_id_gen.get_current_token()
  455. def get_room_min_stream_ordering(self):
  456. return self._backfill_id_gen.get_current_token()
  457. def get_stream_token_for_event(self, event_id):
  458. """The stream token for an event
  459. Args:
  460. event_id(str): The id of the event to look up a stream token for.
  461. Raises:
  462. StoreError if the event wasn't in the database.
  463. Returns:
  464. A deferred "s%d" stream token.
  465. """
  466. return self._simple_select_one_onecol(
  467. table="events",
  468. keyvalues={"event_id": event_id},
  469. retcol="stream_ordering",
  470. ).addCallback(lambda row: "s%d" % (row,))
  471. def get_topological_token_for_event(self, event_id):
  472. """The stream token for an event
  473. Args:
  474. event_id(str): The id of the event to look up a stream token for.
  475. Raises:
  476. StoreError if the event wasn't in the database.
  477. Returns:
  478. A deferred "t%d-%d" topological token.
  479. """
  480. return self._simple_select_one(
  481. table="events",
  482. keyvalues={"event_id": event_id},
  483. retcols=("stream_ordering", "topological_ordering"),
  484. desc="get_topological_token_for_event",
  485. ).addCallback(lambda row: "t%d-%d" % (
  486. row["topological_ordering"], row["stream_ordering"],)
  487. )
  488. def get_max_topological_token(self, room_id, stream_key):
  489. sql = (
  490. "SELECT max(topological_ordering) FROM events"
  491. " WHERE room_id = ? AND stream_ordering < ?"
  492. )
  493. return self._execute(
  494. "get_max_topological_token", None,
  495. sql, room_id, stream_key,
  496. ).addCallback(
  497. lambda r: r[0][0] if r else 0
  498. )
  499. def _get_max_topological_txn(self, txn, room_id):
  500. txn.execute(
  501. "SELECT MAX(topological_ordering) FROM events"
  502. " WHERE room_id = ?",
  503. (room_id,)
  504. )
  505. rows = txn.fetchall()
  506. return rows[0][0] if rows else 0
  507. @staticmethod
  508. def _set_before_and_after(events, rows, topo_order=True):
  509. for event, row in zip(events, rows):
  510. stream = row["stream_ordering"]
  511. if topo_order:
  512. topo = event.depth
  513. else:
  514. topo = None
  515. internal = event.internal_metadata
  516. internal.before = str(RoomStreamToken(topo, stream - 1))
  517. internal.after = str(RoomStreamToken(topo, stream))
  518. internal.order = (
  519. int(topo) if topo else 0,
  520. int(stream),
  521. )
  522. @defer.inlineCallbacks
  523. def get_events_around(self, room_id, event_id, before_limit, after_limit):
  524. """Retrieve events and pagination tokens around a given event in a
  525. room.
  526. Args:
  527. room_id (str)
  528. event_id (str)
  529. before_limit (int)
  530. after_limit (int)
  531. Returns:
  532. dict
  533. """
  534. results = yield self.runInteraction(
  535. "get_events_around", self._get_events_around_txn,
  536. room_id, event_id, before_limit, after_limit
  537. )
  538. events_before = yield self._get_events(
  539. [e for e in results["before"]["event_ids"]],
  540. get_prev_content=True
  541. )
  542. events_after = yield self._get_events(
  543. [e for e in results["after"]["event_ids"]],
  544. get_prev_content=True
  545. )
  546. defer.returnValue({
  547. "events_before": events_before,
  548. "events_after": events_after,
  549. "start": results["before"]["token"],
  550. "end": results["after"]["token"],
  551. })
  552. def _get_events_around_txn(self, txn, room_id, event_id, before_limit, after_limit):
  553. """Retrieves event_ids and pagination tokens around a given event in a
  554. room.
  555. Args:
  556. room_id (str)
  557. event_id (str)
  558. before_limit (int)
  559. after_limit (int)
  560. Returns:
  561. dict
  562. """
  563. results = self._simple_select_one_txn(
  564. txn,
  565. "events",
  566. keyvalues={
  567. "event_id": event_id,
  568. "room_id": room_id,
  569. },
  570. retcols=["stream_ordering", "topological_ordering"],
  571. )
  572. token = RoomStreamToken(
  573. results["topological_ordering"],
  574. results["stream_ordering"],
  575. )
  576. if isinstance(self.database_engine, Sqlite3Engine):
  577. # SQLite3 doesn't optimise ``(x < a) OR (x = a AND y < b)``
  578. # So we give pass it to SQLite3 as the UNION ALL of the two queries.
  579. query_before = (
  580. "SELECT topological_ordering, stream_ordering, event_id FROM events"
  581. " WHERE room_id = ? AND topological_ordering < ?"
  582. " UNION ALL"
  583. " SELECT topological_ordering, stream_ordering, event_id FROM events"
  584. " WHERE room_id = ? AND topological_ordering = ? AND stream_ordering < ?"
  585. " ORDER BY topological_ordering DESC, stream_ordering DESC LIMIT ?"
  586. )
  587. before_args = (
  588. room_id, token.topological,
  589. room_id, token.topological, token.stream,
  590. before_limit,
  591. )
  592. query_after = (
  593. "SELECT topological_ordering, stream_ordering, event_id FROM events"
  594. " WHERE room_id = ? AND topological_ordering > ?"
  595. " UNION ALL"
  596. " SELECT topological_ordering, stream_ordering, event_id FROM events"
  597. " WHERE room_id = ? AND topological_ordering = ? AND stream_ordering > ?"
  598. " ORDER BY topological_ordering ASC, stream_ordering ASC LIMIT ?"
  599. )
  600. after_args = (
  601. room_id, token.topological,
  602. room_id, token.topological, token.stream,
  603. after_limit,
  604. )
  605. else:
  606. query_before = (
  607. "SELECT topological_ordering, stream_ordering, event_id FROM events"
  608. " WHERE room_id = ? AND %s"
  609. " ORDER BY topological_ordering DESC, stream_ordering DESC LIMIT ?"
  610. ) % (upper_bound(token, self.database_engine, inclusive=False),)
  611. before_args = (room_id, before_limit)
  612. query_after = (
  613. "SELECT topological_ordering, stream_ordering, event_id FROM events"
  614. " WHERE room_id = ? AND %s"
  615. " ORDER BY topological_ordering ASC, stream_ordering ASC LIMIT ?"
  616. ) % (lower_bound(token, self.database_engine, inclusive=False),)
  617. after_args = (room_id, after_limit)
  618. txn.execute(query_before, before_args)
  619. rows = self.cursor_to_dict(txn)
  620. events_before = [r["event_id"] for r in rows]
  621. if rows:
  622. start_token = str(RoomStreamToken(
  623. rows[0]["topological_ordering"],
  624. rows[0]["stream_ordering"] - 1,
  625. ))
  626. else:
  627. start_token = str(RoomStreamToken(
  628. token.topological,
  629. token.stream - 1,
  630. ))
  631. txn.execute(query_after, after_args)
  632. rows = self.cursor_to_dict(txn)
  633. events_after = [r["event_id"] for r in rows]
  634. if rows:
  635. end_token = str(RoomStreamToken(
  636. rows[-1]["topological_ordering"],
  637. rows[-1]["stream_ordering"],
  638. ))
  639. else:
  640. end_token = str(token)
  641. return {
  642. "before": {
  643. "event_ids": events_before,
  644. "token": start_token,
  645. },
  646. "after": {
  647. "event_ids": events_after,
  648. "token": end_token,
  649. },
  650. }
  651. @defer.inlineCallbacks
  652. def get_all_new_events_stream(self, from_id, current_id, limit):
  653. """Get all new events"""
  654. def get_all_new_events_stream_txn(txn):
  655. sql = (
  656. "SELECT e.stream_ordering, e.event_id"
  657. " FROM events AS e"
  658. " WHERE"
  659. " ? < e.stream_ordering AND e.stream_ordering <= ?"
  660. " ORDER BY e.stream_ordering ASC"
  661. " LIMIT ?"
  662. )
  663. txn.execute(sql, (from_id, current_id, limit))
  664. rows = txn.fetchall()
  665. upper_bound = current_id
  666. if len(rows) == limit:
  667. upper_bound = rows[-1][0]
  668. return upper_bound, [row[1] for row in rows]
  669. upper_bound, event_ids = yield self.runInteraction(
  670. "get_all_new_events_stream", get_all_new_events_stream_txn,
  671. )
  672. events = yield self._get_events(event_ids)
  673. defer.returnValue((upper_bound, events))
  674. def get_federation_out_pos(self, typ):
  675. return self._simple_select_one_onecol(
  676. table="federation_stream_position",
  677. retcol="stream_id",
  678. keyvalues={"type": typ},
  679. desc="get_federation_out_pos"
  680. )
  681. def update_federation_out_pos(self, typ, stream_id):
  682. return self._simple_update_one(
  683. table="federation_stream_position",
  684. keyvalues={"type": typ},
  685. updatevalues={"stream_id": stream_id},
  686. desc="update_federation_out_pos",
  687. )