stream.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  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 synapse.storage._base import SQLBaseStore
  33. from synapse.storage.events import EventsWorkerStore
  34. from synapse.types import RoomStreamToken
  35. from synapse.util.caches.stream_change_cache import StreamChangeCache
  36. from synapse.util.logcontext import make_deferred_yieldable, run_in_background
  37. from synapse.storage.engines import PostgresEngine
  38. import abc
  39. import logging
  40. from six.moves import range
  41. from collections import namedtuple
  42. logger = logging.getLogger(__name__)
  43. MAX_STREAM_SIZE = 1000
  44. _STREAM_TOKEN = "stream"
  45. _TOPOLOGICAL_TOKEN = "topological"
  46. # Used as return values for pagination APIs
  47. _EventDictReturn = namedtuple("_EventDictReturn", (
  48. "event_id", "topological_ordering", "stream_ordering",
  49. ))
  50. def lower_bound(token, engine, inclusive=False):
  51. inclusive = "=" if inclusive else ""
  52. if token.topological is None:
  53. return "(%d <%s %s)" % (token.stream, inclusive, "stream_ordering")
  54. else:
  55. if isinstance(engine, PostgresEngine):
  56. # Postgres doesn't optimise ``(x < a) OR (x=a AND y<b)`` as well
  57. # as it optimises ``(x,y) < (a,b)`` on multicolumn indexes. So we
  58. # use the later form when running against postgres.
  59. return "((%d,%d) <%s (%s,%s))" % (
  60. token.topological, token.stream, inclusive,
  61. "topological_ordering", "stream_ordering",
  62. )
  63. return "(%d < %s OR (%d = %s AND %d <%s %s))" % (
  64. token.topological, "topological_ordering",
  65. token.topological, "topological_ordering",
  66. token.stream, inclusive, "stream_ordering",
  67. )
  68. def upper_bound(token, engine, inclusive=True):
  69. inclusive = "=" if inclusive else ""
  70. if token.topological is None:
  71. return "(%d >%s %s)" % (token.stream, inclusive, "stream_ordering")
  72. else:
  73. if isinstance(engine, PostgresEngine):
  74. # Postgres doesn't optimise ``(x > a) OR (x=a AND y>b)`` as well
  75. # as it optimises ``(x,y) > (a,b)`` on multicolumn indexes. So we
  76. # use the later form when running against postgres.
  77. return "((%d,%d) >%s (%s,%s))" % (
  78. token.topological, token.stream, inclusive,
  79. "topological_ordering", "stream_ordering",
  80. )
  81. return "(%d > %s OR (%d = %s AND %d >%s %s))" % (
  82. token.topological, "topological_ordering",
  83. token.topological, "topological_ordering",
  84. token.stream, inclusive, "stream_ordering",
  85. )
  86. def filter_to_clause(event_filter):
  87. # NB: This may create SQL clauses that don't optimise well (and we don't
  88. # have indices on all possible clauses). E.g. it may create
  89. # "room_id == X AND room_id != X", which postgres doesn't optimise.
  90. if not event_filter:
  91. return "", []
  92. clauses = []
  93. args = []
  94. if event_filter.types:
  95. clauses.append(
  96. "(%s)" % " OR ".join("type = ?" for _ in event_filter.types)
  97. )
  98. args.extend(event_filter.types)
  99. for typ in event_filter.not_types:
  100. clauses.append("type != ?")
  101. args.append(typ)
  102. if event_filter.senders:
  103. clauses.append(
  104. "(%s)" % " OR ".join("sender = ?" for _ in event_filter.senders)
  105. )
  106. args.extend(event_filter.senders)
  107. for sender in event_filter.not_senders:
  108. clauses.append("sender != ?")
  109. args.append(sender)
  110. if event_filter.rooms:
  111. clauses.append(
  112. "(%s)" % " OR ".join("room_id = ?" for _ in event_filter.rooms)
  113. )
  114. args.extend(event_filter.rooms)
  115. for room_id in event_filter.not_rooms:
  116. clauses.append("room_id != ?")
  117. args.append(room_id)
  118. if event_filter.contains_url:
  119. clauses.append("contains_url = ?")
  120. args.append(event_filter.contains_url)
  121. return " AND ".join(clauses), args
  122. class StreamWorkerStore(EventsWorkerStore, SQLBaseStore):
  123. """This is an abstract base class where subclasses must implement
  124. `get_room_max_stream_ordering` and `get_room_min_stream_ordering`
  125. which can be called in the initializer.
  126. """
  127. __metaclass__ = abc.ABCMeta
  128. def __init__(self, db_conn, hs):
  129. super(StreamWorkerStore, self).__init__(db_conn, hs)
  130. events_max = self.get_room_max_stream_ordering()
  131. event_cache_prefill, min_event_val = self._get_cache_dict(
  132. db_conn, "events",
  133. entity_column="room_id",
  134. stream_column="stream_ordering",
  135. max_value=events_max,
  136. )
  137. self._events_stream_cache = StreamChangeCache(
  138. "EventsRoomStreamChangeCache", min_event_val,
  139. prefilled_cache=event_cache_prefill,
  140. )
  141. self._membership_stream_cache = StreamChangeCache(
  142. "MembershipStreamChangeCache", events_max,
  143. )
  144. self._stream_order_on_start = self.get_room_max_stream_ordering()
  145. @abc.abstractmethod
  146. def get_room_max_stream_ordering(self):
  147. raise NotImplementedError()
  148. @abc.abstractmethod
  149. def get_room_min_stream_ordering(self):
  150. raise NotImplementedError()
  151. @defer.inlineCallbacks
  152. def get_room_events_stream_for_rooms(self, room_ids, from_key, to_key, limit=0,
  153. order='DESC'):
  154. from_id = RoomStreamToken.parse_stream_token(from_key).stream
  155. room_ids = yield self._events_stream_cache.get_entities_changed(
  156. room_ids, from_id
  157. )
  158. if not room_ids:
  159. defer.returnValue({})
  160. results = {}
  161. room_ids = list(room_ids)
  162. for rm_ids in (room_ids[i:i + 20] for i in range(0, len(room_ids), 20)):
  163. res = yield make_deferred_yieldable(defer.gatherResults([
  164. run_in_background(
  165. self.get_room_events_stream_for_room,
  166. room_id, from_key, to_key, limit, order=order,
  167. )
  168. for room_id in rm_ids
  169. ], consumeErrors=True))
  170. results.update(dict(zip(rm_ids, res)))
  171. defer.returnValue(results)
  172. def get_rooms_that_changed(self, room_ids, from_key):
  173. """Given a list of rooms and a token, return rooms where there may have
  174. been changes.
  175. Args:
  176. room_ids (list)
  177. from_key (str): The room_key portion of a StreamToken
  178. """
  179. from_key = RoomStreamToken.parse_stream_token(from_key).stream
  180. return set(
  181. room_id for room_id in room_ids
  182. if self._events_stream_cache.has_entity_changed(room_id, from_key)
  183. )
  184. @defer.inlineCallbacks
  185. def get_room_events_stream_for_room(self, room_id, from_key, to_key, limit=0,
  186. order='DESC'):
  187. """Get new room events in stream ordering since `from_key`.
  188. Args:
  189. room_id (str)
  190. from_key (str): Token from which no events are returned before
  191. to_key (str): Token from which no events are returned after. (This
  192. is typically the current stream token)
  193. limit (int): Maximum number of events to return
  194. order (str): Either "DESC" or "ASC". Determines which events are
  195. returned when the result is limited. If "DESC" then the most
  196. recent `limit` events are returned, otherwise returns the
  197. oldest `limit` events.
  198. Returns:
  199. Deferred[tuple[list[FrozenEvent], str]]: Returns the list of
  200. events (in ascending order) and the token from the start of
  201. the chunk of events returned.
  202. """
  203. if from_key == to_key:
  204. defer.returnValue(([], from_key))
  205. from_id = RoomStreamToken.parse_stream_token(from_key).stream
  206. to_id = RoomStreamToken.parse_stream_token(to_key).stream
  207. has_changed = yield self._events_stream_cache.has_entity_changed(
  208. room_id, from_id
  209. )
  210. if not has_changed:
  211. defer.returnValue(([], from_key))
  212. def f(txn):
  213. sql = (
  214. "SELECT event_id, stream_ordering FROM events WHERE"
  215. " room_id = ?"
  216. " AND not outlier"
  217. " AND stream_ordering > ? AND stream_ordering <= ?"
  218. " ORDER BY stream_ordering %s LIMIT ?"
  219. ) % (order,)
  220. txn.execute(sql, (room_id, from_id, to_id, limit))
  221. rows = [_EventDictReturn(row[0], None, row[1]) for row in txn]
  222. return rows
  223. rows = yield self.runInteraction("get_room_events_stream_for_room", f)
  224. ret = yield self._get_events(
  225. [r.event_id for r in rows],
  226. get_prev_content=True
  227. )
  228. self._set_before_and_after(ret, rows, topo_order=from_id is None)
  229. if order.lower() == "desc":
  230. ret.reverse()
  231. if rows:
  232. key = "s%d" % min(r.stream_ordering for r in rows)
  233. else:
  234. # Assume we didn't get anything because there was nothing to
  235. # get.
  236. key = from_key
  237. defer.returnValue((ret, key))
  238. @defer.inlineCallbacks
  239. def get_membership_changes_for_user(self, user_id, from_key, to_key):
  240. from_id = RoomStreamToken.parse_stream_token(from_key).stream
  241. to_id = RoomStreamToken.parse_stream_token(to_key).stream
  242. if from_key == to_key:
  243. defer.returnValue([])
  244. if from_id:
  245. has_changed = self._membership_stream_cache.has_entity_changed(
  246. user_id, int(from_id)
  247. )
  248. if not has_changed:
  249. defer.returnValue([])
  250. def f(txn):
  251. sql = (
  252. "SELECT m.event_id, stream_ordering FROM events AS e,"
  253. " room_memberships AS m"
  254. " WHERE e.event_id = m.event_id"
  255. " AND m.user_id = ?"
  256. " AND e.stream_ordering > ? AND e.stream_ordering <= ?"
  257. " ORDER BY e.stream_ordering ASC"
  258. )
  259. txn.execute(sql, (user_id, from_id, to_id,))
  260. rows = [_EventDictReturn(row[0], None, row[1]) for row in txn]
  261. return rows
  262. rows = yield self.runInteraction("get_membership_changes_for_user", f)
  263. ret = yield self._get_events(
  264. [r.event_id for r in rows],
  265. get_prev_content=True
  266. )
  267. self._set_before_and_after(ret, rows, topo_order=False)
  268. defer.returnValue(ret)
  269. @defer.inlineCallbacks
  270. def get_recent_events_for_room(self, room_id, limit, end_token):
  271. """Get the most recent events in the room in topological ordering.
  272. Args:
  273. room_id (str)
  274. limit (int)
  275. end_token (str): The stream token representing now.
  276. Returns:
  277. Deferred[tuple[list[FrozenEvent], str]]: Returns a list of
  278. events and a token pointing to the start of the returned
  279. events.
  280. The events returned are in ascending order.
  281. """
  282. rows, token = yield self.get_recent_event_ids_for_room(
  283. room_id, limit, end_token,
  284. )
  285. logger.debug("stream before")
  286. events = yield self._get_events(
  287. [r.event_id for r in rows],
  288. get_prev_content=True
  289. )
  290. logger.debug("stream after")
  291. self._set_before_and_after(events, rows)
  292. defer.returnValue((events, token))
  293. @defer.inlineCallbacks
  294. def get_recent_event_ids_for_room(self, room_id, limit, end_token):
  295. """Get the most recent events in the room in topological ordering.
  296. Args:
  297. room_id (str)
  298. limit (int)
  299. end_token (str): The stream token representing now.
  300. Returns:
  301. Deferred[tuple[list[_EventDictReturn], str]]: Returns a list of
  302. _EventDictReturn and a token pointing to the start of the returned
  303. events.
  304. The events returned are in ascending order.
  305. """
  306. # Allow a zero limit here, and no-op.
  307. if limit == 0:
  308. defer.returnValue(([], end_token))
  309. end_token = RoomStreamToken.parse(end_token)
  310. rows, token = yield self.runInteraction(
  311. "get_recent_event_ids_for_room", self._paginate_room_events_txn,
  312. room_id, from_token=end_token, limit=limit,
  313. )
  314. # We want to return the results in ascending order.
  315. rows.reverse()
  316. defer.returnValue((rows, token))
  317. def get_room_event_after_stream_ordering(self, room_id, stream_ordering):
  318. """Gets details of the first event in a room at or after a stream ordering
  319. Args:
  320. room_id (str):
  321. stream_ordering (int):
  322. Returns:
  323. Deferred[(int, int, str)]:
  324. (stream ordering, topological ordering, event_id)
  325. """
  326. def _f(txn):
  327. sql = (
  328. "SELECT stream_ordering, topological_ordering, event_id"
  329. " FROM events"
  330. " WHERE room_id = ? AND stream_ordering >= ?"
  331. " AND NOT outlier"
  332. " ORDER BY stream_ordering"
  333. " LIMIT 1"
  334. )
  335. txn.execute(sql, (room_id, stream_ordering, ))
  336. return txn.fetchone()
  337. return self.runInteraction(
  338. "get_room_event_after_stream_ordering", _f,
  339. )
  340. @defer.inlineCallbacks
  341. def get_room_events_max_id(self, room_id=None):
  342. """Returns the current token for rooms stream.
  343. By default, it returns the current global stream token. Specifying a
  344. `room_id` causes it to return the current room specific topological
  345. token.
  346. """
  347. token = yield self.get_room_max_stream_ordering()
  348. if room_id is None:
  349. defer.returnValue("s%d" % (token,))
  350. else:
  351. topo = yield self.runInteraction(
  352. "_get_max_topological_txn", self._get_max_topological_txn,
  353. room_id,
  354. )
  355. defer.returnValue("t%d-%d" % (topo, token))
  356. def get_stream_token_for_event(self, event_id):
  357. """The stream token for an event
  358. Args:
  359. event_id(str): The id of the event to look up a stream token for.
  360. Raises:
  361. StoreError if the event wasn't in the database.
  362. Returns:
  363. A deferred "s%d" stream token.
  364. """
  365. return self._simple_select_one_onecol(
  366. table="events",
  367. keyvalues={"event_id": event_id},
  368. retcol="stream_ordering",
  369. ).addCallback(lambda row: "s%d" % (row,))
  370. def get_topological_token_for_event(self, event_id):
  371. """The stream token for an event
  372. Args:
  373. event_id(str): The id of the event to look up a stream token for.
  374. Raises:
  375. StoreError if the event wasn't in the database.
  376. Returns:
  377. A deferred "t%d-%d" topological token.
  378. """
  379. return self._simple_select_one(
  380. table="events",
  381. keyvalues={"event_id": event_id},
  382. retcols=("stream_ordering", "topological_ordering"),
  383. desc="get_topological_token_for_event",
  384. ).addCallback(lambda row: "t%d-%d" % (
  385. row["topological_ordering"], row["stream_ordering"],)
  386. )
  387. def get_max_topological_token(self, room_id, stream_key):
  388. sql = (
  389. "SELECT max(topological_ordering) FROM events"
  390. " WHERE room_id = ? AND stream_ordering < ?"
  391. )
  392. return self._execute(
  393. "get_max_topological_token", None,
  394. sql, room_id, stream_key,
  395. ).addCallback(
  396. lambda r: r[0][0] if r else 0
  397. )
  398. def _get_max_topological_txn(self, txn, room_id):
  399. txn.execute(
  400. "SELECT MAX(topological_ordering) FROM events"
  401. " WHERE room_id = ?",
  402. (room_id,)
  403. )
  404. rows = txn.fetchall()
  405. return rows[0][0] if rows else 0
  406. @staticmethod
  407. def _set_before_and_after(events, rows, topo_order=True):
  408. """Inserts ordering information to events' internal metadata from
  409. the DB rows.
  410. Args:
  411. events (list[FrozenEvent])
  412. rows (list[_EventDictReturn])
  413. topo_order (bool): Whether the events were ordered topologically
  414. or by stream ordering. If true then all rows should have a non
  415. null topological_ordering.
  416. """
  417. for event, row in zip(events, rows):
  418. stream = row.stream_ordering
  419. if topo_order and row.topological_ordering:
  420. topo = row.topological_ordering
  421. else:
  422. topo = None
  423. internal = event.internal_metadata
  424. internal.before = str(RoomStreamToken(topo, stream - 1))
  425. internal.after = str(RoomStreamToken(topo, stream))
  426. internal.order = (
  427. int(topo) if topo else 0,
  428. int(stream),
  429. )
  430. @defer.inlineCallbacks
  431. def get_events_around(self, room_id, event_id, before_limit, after_limit):
  432. """Retrieve events and pagination tokens around a given event in a
  433. room.
  434. Args:
  435. room_id (str)
  436. event_id (str)
  437. before_limit (int)
  438. after_limit (int)
  439. Returns:
  440. dict
  441. """
  442. results = yield self.runInteraction(
  443. "get_events_around", self._get_events_around_txn,
  444. room_id, event_id, before_limit, after_limit
  445. )
  446. events_before = yield self._get_events(
  447. [e for e in results["before"]["event_ids"]],
  448. get_prev_content=True
  449. )
  450. events_after = yield self._get_events(
  451. [e for e in results["after"]["event_ids"]],
  452. get_prev_content=True
  453. )
  454. defer.returnValue({
  455. "events_before": events_before,
  456. "events_after": events_after,
  457. "start": results["before"]["token"],
  458. "end": results["after"]["token"],
  459. })
  460. def _get_events_around_txn(self, txn, room_id, event_id, before_limit, after_limit):
  461. """Retrieves event_ids and pagination tokens around a given event in a
  462. room.
  463. Args:
  464. room_id (str)
  465. event_id (str)
  466. before_limit (int)
  467. after_limit (int)
  468. Returns:
  469. dict
  470. """
  471. results = self._simple_select_one_txn(
  472. txn,
  473. "events",
  474. keyvalues={
  475. "event_id": event_id,
  476. "room_id": room_id,
  477. },
  478. retcols=["stream_ordering", "topological_ordering"],
  479. )
  480. # Paginating backwards includes the event at the token, but paginating
  481. # forward doesn't.
  482. before_token = RoomStreamToken(
  483. results["topological_ordering"] - 1,
  484. results["stream_ordering"],
  485. )
  486. after_token = RoomStreamToken(
  487. results["topological_ordering"],
  488. results["stream_ordering"],
  489. )
  490. rows, start_token = self._paginate_room_events_txn(
  491. txn, room_id, before_token, direction='b', limit=before_limit,
  492. )
  493. events_before = [r.event_id for r in rows]
  494. rows, end_token = self._paginate_room_events_txn(
  495. txn, room_id, after_token, direction='f', limit=after_limit,
  496. )
  497. events_after = [r.event_id for r in rows]
  498. return {
  499. "before": {
  500. "event_ids": events_before,
  501. "token": start_token,
  502. },
  503. "after": {
  504. "event_ids": events_after,
  505. "token": end_token,
  506. },
  507. }
  508. @defer.inlineCallbacks
  509. def get_all_new_events_stream(self, from_id, current_id, limit):
  510. """Get all new events"""
  511. def get_all_new_events_stream_txn(txn):
  512. sql = (
  513. "SELECT e.stream_ordering, e.event_id"
  514. " FROM events AS e"
  515. " WHERE"
  516. " ? < e.stream_ordering AND e.stream_ordering <= ?"
  517. " ORDER BY e.stream_ordering ASC"
  518. " LIMIT ?"
  519. )
  520. txn.execute(sql, (from_id, current_id, limit))
  521. rows = txn.fetchall()
  522. upper_bound = current_id
  523. if len(rows) == limit:
  524. upper_bound = rows[-1][0]
  525. return upper_bound, [row[1] for row in rows]
  526. upper_bound, event_ids = yield self.runInteraction(
  527. "get_all_new_events_stream", get_all_new_events_stream_txn,
  528. )
  529. events = yield self._get_events(event_ids)
  530. defer.returnValue((upper_bound, events))
  531. def get_federation_out_pos(self, typ):
  532. return self._simple_select_one_onecol(
  533. table="federation_stream_position",
  534. retcol="stream_id",
  535. keyvalues={"type": typ},
  536. desc="get_federation_out_pos"
  537. )
  538. def update_federation_out_pos(self, typ, stream_id):
  539. return self._simple_update_one(
  540. table="federation_stream_position",
  541. keyvalues={"type": typ},
  542. updatevalues={"stream_id": stream_id},
  543. desc="update_federation_out_pos",
  544. )
  545. def has_room_changed_since(self, room_id, stream_id):
  546. return self._events_stream_cache.has_entity_changed(room_id, stream_id)
  547. def _paginate_room_events_txn(self, txn, room_id, from_token, to_token=None,
  548. direction='b', limit=-1, event_filter=None):
  549. """Returns list of events before or after a given token.
  550. Args:
  551. txn
  552. room_id (str)
  553. from_token (RoomStreamToken): The token used to stream from
  554. to_token (RoomStreamToken|None): A token which if given limits the
  555. results to only those before
  556. direction(char): Either 'b' or 'f' to indicate whether we are
  557. paginating forwards or backwards from `from_key`.
  558. limit (int): The maximum number of events to return.
  559. event_filter (Filter|None): If provided filters the events to
  560. those that match the filter.
  561. Returns:
  562. Deferred[tuple[list[_EventDictReturn], str]]: Returns the results
  563. as a list of _EventDictReturn and a token that points to the end
  564. of the result set.
  565. """
  566. assert int(limit) >= 0
  567. # Tokens really represent positions between elements, but we use
  568. # the convention of pointing to the event before the gap. Hence
  569. # we have a bit of asymmetry when it comes to equalities.
  570. args = [False, room_id]
  571. if direction == 'b':
  572. order = "DESC"
  573. bounds = upper_bound(
  574. from_token, self.database_engine
  575. )
  576. if to_token:
  577. bounds = "%s AND %s" % (bounds, lower_bound(
  578. to_token, self.database_engine
  579. ))
  580. else:
  581. order = "ASC"
  582. bounds = lower_bound(
  583. from_token, self.database_engine
  584. )
  585. if to_token:
  586. bounds = "%s AND %s" % (bounds, upper_bound(
  587. to_token, self.database_engine
  588. ))
  589. filter_clause, filter_args = filter_to_clause(event_filter)
  590. if filter_clause:
  591. bounds += " AND " + filter_clause
  592. args.extend(filter_args)
  593. args.append(int(limit))
  594. sql = (
  595. "SELECT event_id, topological_ordering, stream_ordering"
  596. " FROM events"
  597. " WHERE outlier = ? AND room_id = ? AND %(bounds)s"
  598. " ORDER BY topological_ordering %(order)s,"
  599. " stream_ordering %(order)s LIMIT ?"
  600. ) % {
  601. "bounds": bounds,
  602. "order": order,
  603. }
  604. txn.execute(sql, args)
  605. rows = [_EventDictReturn(row[0], row[1], row[2]) for row in txn]
  606. if rows:
  607. topo = rows[-1].topological_ordering
  608. toke = rows[-1].stream_ordering
  609. if direction == 'b':
  610. # Tokens are positions between events.
  611. # This token points *after* the last event in the chunk.
  612. # We need it to point to the event before it in the chunk
  613. # when we are going backwards so we subtract one from the
  614. # stream part.
  615. toke -= 1
  616. next_token = RoomStreamToken(topo, toke)
  617. else:
  618. # TODO (erikj): We should work out what to do here instead.
  619. next_token = to_token if to_token else from_token
  620. return rows, str(next_token),
  621. @defer.inlineCallbacks
  622. def paginate_room_events(self, room_id, from_key, to_key=None,
  623. direction='b', limit=-1, event_filter=None):
  624. """Returns list of events before or after a given token.
  625. Args:
  626. room_id (str)
  627. from_key (str): The token used to stream from
  628. to_key (str|None): A token which if given limits the results to
  629. only those before
  630. direction(char): Either 'b' or 'f' to indicate whether we are
  631. paginating forwards or backwards from `from_key`.
  632. limit (int): The maximum number of events to return. Zero or less
  633. means no limit.
  634. event_filter (Filter|None): If provided filters the events to
  635. those that match the filter.
  636. Returns:
  637. tuple[list[dict], str]: Returns the results as a list of dicts and
  638. a token that points to the end of the result set. The dicts have
  639. the keys "event_id", "topological_ordering" and "stream_orderign".
  640. """
  641. from_key = RoomStreamToken.parse(from_key)
  642. if to_key:
  643. to_key = RoomStreamToken.parse(to_key)
  644. rows, token = yield self.runInteraction(
  645. "paginate_room_events", self._paginate_room_events_txn,
  646. room_id, from_key, to_key, direction, limit, event_filter,
  647. )
  648. events = yield self._get_events(
  649. [r.event_id for r in rows],
  650. get_prev_content=True
  651. )
  652. self._set_before_and_after(events, rows)
  653. defer.returnValue((events, token))
  654. class StreamStore(StreamWorkerStore):
  655. def get_room_max_stream_ordering(self):
  656. return self._stream_id_gen.get_current_token()
  657. def get_room_min_stream_ordering(self):
  658. return self._backfill_id_gen.get_current_token()