stream.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2017 Vector Creations Ltd
  4. # Copyright 2018-2019 New Vector Ltd
  5. # Copyright 2019 The Matrix.org Foundation C.I.C.
  6. #
  7. # Licensed under the Apache License, Version 2.0 (the "License");
  8. # you may not use this file except in compliance with the License.
  9. # You may obtain a copy of the License at
  10. #
  11. # http://www.apache.org/licenses/LICENSE-2.0
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS,
  15. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. """ This module is responsible for getting events from the DB for pagination
  19. and event streaming.
  20. The order it returns events in depend on whether we are streaming forwards or
  21. are paginating backwards. We do this because we want to handle out of order
  22. messages nicely, while still returning them in the correct order when we
  23. paginate bacwards.
  24. This is implemented by keeping two ordering columns: stream_ordering and
  25. topological_ordering. Stream ordering is basically insertion/received order
  26. (except for events from backfill requests). The topological_ordering is a
  27. weak ordering of events based on the pdu graph.
  28. This means that we have to have two different types of tokens, depending on
  29. what sort order was used:
  30. - stream tokens are of the form: "s%d", which maps directly to the column
  31. - topological tokems: "t%d-%d", where the integers map to the topological
  32. and stream ordering columns respectively.
  33. """
  34. import abc
  35. import logging
  36. from collections import namedtuple
  37. from twisted.internet import defer
  38. from synapse.logging.context import make_deferred_yieldable, run_in_background
  39. from synapse.storage._base import SQLBaseStore
  40. from synapse.storage.data_stores.main.events_worker import EventsWorkerStore
  41. from synapse.storage.database import Database
  42. from synapse.storage.engines import PostgresEngine
  43. from synapse.types import RoomStreamToken
  44. from synapse.util.caches.stream_change_cache import StreamChangeCache
  45. logger = logging.getLogger(__name__)
  46. MAX_STREAM_SIZE = 1000
  47. _STREAM_TOKEN = "stream"
  48. _TOPOLOGICAL_TOKEN = "topological"
  49. # Used as return values for pagination APIs
  50. _EventDictReturn = namedtuple(
  51. "_EventDictReturn", ("event_id", "topological_ordering", "stream_ordering")
  52. )
  53. def generate_pagination_where_clause(
  54. direction, column_names, from_token, to_token, engine
  55. ):
  56. """Creates an SQL expression to bound the columns by the pagination
  57. tokens.
  58. For example creates an SQL expression like:
  59. (6, 7) >= (topological_ordering, stream_ordering)
  60. AND (5, 3) < (topological_ordering, stream_ordering)
  61. would be generated for dir=b, from_token=(6, 7) and to_token=(5, 3).
  62. Note that tokens are considered to be after the row they are in, e.g. if
  63. a row A has a token T, then we consider A to be before T. This convention
  64. is important when figuring out inequalities for the generated SQL, and
  65. produces the following result:
  66. - If paginating forwards then we exclude any rows matching the from
  67. token, but include those that match the to token.
  68. - If paginating backwards then we include any rows matching the from
  69. token, but include those that match the to token.
  70. Args:
  71. direction (str): Whether we're paginating backwards("b") or
  72. forwards ("f").
  73. column_names (tuple[str, str]): The column names to bound. Must *not*
  74. be user defined as these get inserted directly into the SQL
  75. statement without escapes.
  76. from_token (tuple[int, int]|None): The start point for the pagination.
  77. This is an exclusive minimum bound if direction is "f", and an
  78. inclusive maximum bound if direction is "b".
  79. to_token (tuple[int, int]|None): The endpoint point for the pagination.
  80. This is an inclusive maximum bound if direction is "f", and an
  81. exclusive minimum bound if direction is "b".
  82. engine: The database engine to generate the clauses for
  83. Returns:
  84. str: The sql expression
  85. """
  86. assert direction in ("b", "f")
  87. where_clause = []
  88. if from_token:
  89. where_clause.append(
  90. _make_generic_sql_bound(
  91. bound=">=" if direction == "b" else "<",
  92. column_names=column_names,
  93. values=from_token,
  94. engine=engine,
  95. )
  96. )
  97. if to_token:
  98. where_clause.append(
  99. _make_generic_sql_bound(
  100. bound="<" if direction == "b" else ">=",
  101. column_names=column_names,
  102. values=to_token,
  103. engine=engine,
  104. )
  105. )
  106. return " AND ".join(where_clause)
  107. def _make_generic_sql_bound(bound, column_names, values, engine):
  108. """Create an SQL expression that bounds the given column names by the
  109. values, e.g. create the equivalent of `(1, 2) < (col1, col2)`.
  110. Only works with two columns.
  111. Older versions of SQLite don't support that syntax so we have to expand it
  112. out manually.
  113. Args:
  114. bound (str): The comparison operator to use. One of ">", "<", ">=",
  115. "<=", where the values are on the left and columns on the right.
  116. names (tuple[str, str]): The column names. Must *not* be user defined
  117. as these get inserted directly into the SQL statement without
  118. escapes.
  119. values (tuple[int|None, int]): The values to bound the columns by. If
  120. the first value is None then only creates a bound on the second
  121. column.
  122. engine: The database engine to generate the SQL for
  123. Returns:
  124. str
  125. """
  126. assert bound in (">", "<", ">=", "<=")
  127. name1, name2 = column_names
  128. val1, val2 = values
  129. if val1 is None:
  130. val2 = int(val2)
  131. return "(%d %s %s)" % (val2, bound, name2)
  132. val1 = int(val1)
  133. val2 = int(val2)
  134. if isinstance(engine, PostgresEngine):
  135. # Postgres doesn't optimise ``(x < a) OR (x=a AND y<b)`` as well
  136. # as it optimises ``(x,y) < (a,b)`` on multicolumn indexes. So we
  137. # use the later form when running against postgres.
  138. return "((%d,%d) %s (%s,%s))" % (val1, val2, bound, name1, name2)
  139. # We want to generate queries of e.g. the form:
  140. #
  141. # (val1 < name1 OR (val1 = name1 AND val2 <= name2))
  142. #
  143. # which is equivalent to (val1, val2) < (name1, name2)
  144. return """(
  145. {val1:d} {strict_bound} {name1}
  146. OR ({val1:d} = {name1} AND {val2:d} {bound} {name2})
  147. )""".format(
  148. name1=name1,
  149. val1=val1,
  150. name2=name2,
  151. val2=val2,
  152. strict_bound=bound[0], # The first bound must always be strict equality here
  153. bound=bound,
  154. )
  155. def filter_to_clause(event_filter):
  156. # NB: This may create SQL clauses that don't optimise well (and we don't
  157. # have indices on all possible clauses). E.g. it may create
  158. # "room_id == X AND room_id != X", which postgres doesn't optimise.
  159. if not event_filter:
  160. return "", []
  161. clauses = []
  162. args = []
  163. if event_filter.types:
  164. clauses.append("(%s)" % " OR ".join("type = ?" for _ in event_filter.types))
  165. args.extend(event_filter.types)
  166. for typ in event_filter.not_types:
  167. clauses.append("type != ?")
  168. args.append(typ)
  169. if event_filter.senders:
  170. clauses.append("(%s)" % " OR ".join("sender = ?" for _ in event_filter.senders))
  171. args.extend(event_filter.senders)
  172. for sender in event_filter.not_senders:
  173. clauses.append("sender != ?")
  174. args.append(sender)
  175. if event_filter.rooms:
  176. clauses.append("(%s)" % " OR ".join("room_id = ?" for _ in event_filter.rooms))
  177. args.extend(event_filter.rooms)
  178. for room_id in event_filter.not_rooms:
  179. clauses.append("room_id != ?")
  180. args.append(room_id)
  181. if event_filter.contains_url:
  182. clauses.append("contains_url = ?")
  183. args.append(event_filter.contains_url)
  184. # We're only applying the "labels" filter on the database query, because applying the
  185. # "not_labels" filter via a SQL query is non-trivial. Instead, we let
  186. # event_filter.check_fields apply it, which is not as efficient but makes the
  187. # implementation simpler.
  188. if event_filter.labels:
  189. clauses.append("(%s)" % " OR ".join("label = ?" for _ in event_filter.labels))
  190. args.extend(event_filter.labels)
  191. return " AND ".join(clauses), args
  192. class StreamWorkerStore(EventsWorkerStore, SQLBaseStore):
  193. """This is an abstract base class where subclasses must implement
  194. `get_room_max_stream_ordering` and `get_room_min_stream_ordering`
  195. which can be called in the initializer.
  196. """
  197. __metaclass__ = abc.ABCMeta
  198. def __init__(self, database: Database, db_conn, hs):
  199. super(StreamWorkerStore, self).__init__(database, db_conn, hs)
  200. events_max = self.get_room_max_stream_ordering()
  201. event_cache_prefill, min_event_val = self.db.get_cache_dict(
  202. db_conn,
  203. "events",
  204. entity_column="room_id",
  205. stream_column="stream_ordering",
  206. max_value=events_max,
  207. )
  208. self._events_stream_cache = StreamChangeCache(
  209. "EventsRoomStreamChangeCache",
  210. min_event_val,
  211. prefilled_cache=event_cache_prefill,
  212. )
  213. self._membership_stream_cache = StreamChangeCache(
  214. "MembershipStreamChangeCache", events_max
  215. )
  216. self._stream_order_on_start = self.get_room_max_stream_ordering()
  217. @abc.abstractmethod
  218. def get_room_max_stream_ordering(self):
  219. raise NotImplementedError()
  220. @abc.abstractmethod
  221. def get_room_min_stream_ordering(self):
  222. raise NotImplementedError()
  223. @defer.inlineCallbacks
  224. def get_room_events_stream_for_rooms(
  225. self, room_ids, from_key, to_key, limit=0, order="DESC"
  226. ):
  227. """Get new room events in stream ordering since `from_key`.
  228. Args:
  229. room_id (str)
  230. from_key (str): Token from which no events are returned before
  231. to_key (str): Token from which no events are returned after. (This
  232. is typically the current stream token)
  233. limit (int): Maximum number of events to return
  234. order (str): Either "DESC" or "ASC". Determines which events are
  235. returned when the result is limited. If "DESC" then the most
  236. recent `limit` events are returned, otherwise returns the
  237. oldest `limit` events.
  238. Returns:
  239. Deferred[dict[str,tuple[list[FrozenEvent], str]]]
  240. A map from room id to a tuple containing:
  241. - list of recent events in the room
  242. - stream ordering key for the start of the chunk of events returned.
  243. """
  244. from_id = RoomStreamToken.parse_stream_token(from_key).stream
  245. room_ids = yield self._events_stream_cache.get_entities_changed(
  246. room_ids, from_id
  247. )
  248. if not room_ids:
  249. return {}
  250. results = {}
  251. room_ids = list(room_ids)
  252. for rm_ids in (room_ids[i : i + 20] for i in range(0, len(room_ids), 20)):
  253. res = yield make_deferred_yieldable(
  254. defer.gatherResults(
  255. [
  256. run_in_background(
  257. self.get_room_events_stream_for_room,
  258. room_id,
  259. from_key,
  260. to_key,
  261. limit,
  262. order=order,
  263. )
  264. for room_id in rm_ids
  265. ],
  266. consumeErrors=True,
  267. )
  268. )
  269. results.update(dict(zip(rm_ids, res)))
  270. return results
  271. def get_rooms_that_changed(self, room_ids, from_key):
  272. """Given a list of rooms and a token, return rooms where there may have
  273. been changes.
  274. Args:
  275. room_ids (list)
  276. from_key (str): The room_key portion of a StreamToken
  277. """
  278. from_key = RoomStreamToken.parse_stream_token(from_key).stream
  279. return {
  280. room_id
  281. for room_id in room_ids
  282. if self._events_stream_cache.has_entity_changed(room_id, from_key)
  283. }
  284. @defer.inlineCallbacks
  285. def get_room_events_stream_for_room(
  286. self, room_id, from_key, to_key, limit=0, order="DESC"
  287. ):
  288. """Get new room events in stream ordering since `from_key`.
  289. Args:
  290. room_id (str)
  291. from_key (str): Token from which no events are returned before
  292. to_key (str): Token from which no events are returned after. (This
  293. is typically the current stream token)
  294. limit (int): Maximum number of events to return
  295. order (str): Either "DESC" or "ASC". Determines which events are
  296. returned when the result is limited. If "DESC" then the most
  297. recent `limit` events are returned, otherwise returns the
  298. oldest `limit` events.
  299. Returns:
  300. Deferred[tuple[list[FrozenEvent], str]]: Returns the list of
  301. events (in ascending order) and the token from the start of
  302. the chunk of events returned.
  303. """
  304. if from_key == to_key:
  305. return [], from_key
  306. from_id = RoomStreamToken.parse_stream_token(from_key).stream
  307. to_id = RoomStreamToken.parse_stream_token(to_key).stream
  308. has_changed = yield self._events_stream_cache.has_entity_changed(
  309. room_id, from_id
  310. )
  311. if not has_changed:
  312. return [], from_key
  313. def f(txn):
  314. sql = (
  315. "SELECT event_id, stream_ordering FROM events WHERE"
  316. " room_id = ?"
  317. " AND not outlier"
  318. " AND stream_ordering > ? AND stream_ordering <= ?"
  319. " ORDER BY stream_ordering %s LIMIT ?"
  320. ) % (order,)
  321. txn.execute(sql, (room_id, from_id, to_id, limit))
  322. rows = [_EventDictReturn(row[0], None, row[1]) for row in txn]
  323. return rows
  324. rows = yield self.db.runInteraction("get_room_events_stream_for_room", f)
  325. ret = yield self.get_events_as_list(
  326. [r.event_id for r in rows], get_prev_content=True
  327. )
  328. self._set_before_and_after(ret, rows, topo_order=from_id is None)
  329. if order.lower() == "desc":
  330. ret.reverse()
  331. if rows:
  332. key = "s%d" % min(r.stream_ordering for r in rows)
  333. else:
  334. # Assume we didn't get anything because there was nothing to
  335. # get.
  336. key = from_key
  337. return ret, key
  338. @defer.inlineCallbacks
  339. def get_membership_changes_for_user(self, user_id, from_key, to_key):
  340. from_id = RoomStreamToken.parse_stream_token(from_key).stream
  341. to_id = RoomStreamToken.parse_stream_token(to_key).stream
  342. if from_key == to_key:
  343. return []
  344. if from_id:
  345. has_changed = self._membership_stream_cache.has_entity_changed(
  346. user_id, int(from_id)
  347. )
  348. if not has_changed:
  349. return []
  350. def f(txn):
  351. sql = (
  352. "SELECT m.event_id, stream_ordering FROM events AS e,"
  353. " room_memberships AS m"
  354. " WHERE e.event_id = m.event_id"
  355. " AND m.user_id = ?"
  356. " AND e.stream_ordering > ? AND e.stream_ordering <= ?"
  357. " ORDER BY e.stream_ordering ASC"
  358. )
  359. txn.execute(sql, (user_id, from_id, to_id))
  360. rows = [_EventDictReturn(row[0], None, row[1]) for row in txn]
  361. return rows
  362. rows = yield self.db.runInteraction("get_membership_changes_for_user", f)
  363. ret = yield self.get_events_as_list(
  364. [r.event_id for r in rows], get_prev_content=True
  365. )
  366. self._set_before_and_after(ret, rows, topo_order=False)
  367. return ret
  368. @defer.inlineCallbacks
  369. def get_recent_events_for_room(self, room_id, limit, end_token):
  370. """Get the most recent events in the room in topological ordering.
  371. Args:
  372. room_id (str)
  373. limit (int)
  374. end_token (str): The stream token representing now.
  375. Returns:
  376. Deferred[tuple[list[FrozenEvent], str]]: Returns a list of
  377. events and a token pointing to the start of the returned
  378. events.
  379. The events returned are in ascending order.
  380. """
  381. rows, token = yield self.get_recent_event_ids_for_room(
  382. room_id, limit, end_token
  383. )
  384. events = yield self.get_events_as_list(
  385. [r.event_id for r in rows], get_prev_content=True
  386. )
  387. self._set_before_and_after(events, rows)
  388. return (events, token)
  389. @defer.inlineCallbacks
  390. def get_recent_event_ids_for_room(self, room_id, limit, end_token):
  391. """Get the most recent events in the room in topological ordering.
  392. Args:
  393. room_id (str)
  394. limit (int)
  395. end_token (str): The stream token representing now.
  396. Returns:
  397. Deferred[tuple[list[_EventDictReturn], str]]: Returns a list of
  398. _EventDictReturn and a token pointing to the start of the returned
  399. events.
  400. The events returned are in ascending order.
  401. """
  402. # Allow a zero limit here, and no-op.
  403. if limit == 0:
  404. return [], end_token
  405. end_token = RoomStreamToken.parse(end_token)
  406. rows, token = yield self.db.runInteraction(
  407. "get_recent_event_ids_for_room",
  408. self._paginate_room_events_txn,
  409. room_id,
  410. from_token=end_token,
  411. limit=limit,
  412. )
  413. # We want to return the results in ascending order.
  414. rows.reverse()
  415. return rows, token
  416. def get_room_event_before_stream_ordering(self, room_id, stream_ordering):
  417. """Gets details of the first event in a room at or before a stream ordering
  418. Args:
  419. room_id (str):
  420. stream_ordering (int):
  421. Returns:
  422. Deferred[(int, int, str)]:
  423. (stream ordering, topological ordering, event_id)
  424. """
  425. def _f(txn):
  426. sql = (
  427. "SELECT stream_ordering, topological_ordering, event_id"
  428. " FROM events"
  429. " WHERE room_id = ? AND stream_ordering <= ?"
  430. " AND NOT outlier"
  431. " ORDER BY stream_ordering DESC"
  432. " LIMIT 1"
  433. )
  434. txn.execute(sql, (room_id, stream_ordering))
  435. return txn.fetchone()
  436. return self.db.runInteraction("get_room_event_before_stream_ordering", _f)
  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.get_room_max_stream_ordering()
  445. if room_id is None:
  446. return "s%d" % (token,)
  447. else:
  448. topo = yield self.db.runInteraction(
  449. "_get_max_topological_txn", self._get_max_topological_txn, room_id
  450. )
  451. return "t%d-%d" % (topo, token)
  452. def get_stream_token_for_event(self, event_id):
  453. """The stream token for an event
  454. Args:
  455. event_id(str): The id of the event to look up a stream token for.
  456. Raises:
  457. StoreError if the event wasn't in the database.
  458. Returns:
  459. A deferred "s%d" stream token.
  460. """
  461. return self.db.simple_select_one_onecol(
  462. table="events", keyvalues={"event_id": event_id}, retcol="stream_ordering"
  463. ).addCallback(lambda row: "s%d" % (row,))
  464. def get_topological_token_for_event(self, event_id):
  465. """The stream token for an event
  466. Args:
  467. event_id(str): The id of the event to look up a stream token for.
  468. Raises:
  469. StoreError if the event wasn't in the database.
  470. Returns:
  471. A deferred "t%d-%d" topological token.
  472. """
  473. return self.db.simple_select_one(
  474. table="events",
  475. keyvalues={"event_id": event_id},
  476. retcols=("stream_ordering", "topological_ordering"),
  477. desc="get_topological_token_for_event",
  478. ).addCallback(
  479. lambda row: "t%d-%d" % (row["topological_ordering"], row["stream_ordering"])
  480. )
  481. def get_max_topological_token(self, room_id, stream_key):
  482. """Get the max topological token in a room before the given stream
  483. ordering.
  484. Args:
  485. room_id (str)
  486. stream_key (int)
  487. Returns:
  488. Deferred[int]
  489. """
  490. sql = (
  491. "SELECT coalesce(max(topological_ordering), 0) FROM events"
  492. " WHERE room_id = ? AND stream_ordering < ?"
  493. )
  494. return self.db.execute(
  495. "get_max_topological_token", None, sql, room_id, stream_key
  496. ).addCallback(lambda r: r[0][0] if r else 0)
  497. def _get_max_topological_txn(self, txn, room_id):
  498. txn.execute(
  499. "SELECT MAX(topological_ordering) FROM events WHERE room_id = ?",
  500. (room_id,),
  501. )
  502. rows = txn.fetchall()
  503. return rows[0][0] if rows else 0
  504. @staticmethod
  505. def _set_before_and_after(events, rows, topo_order=True):
  506. """Inserts ordering information to events' internal metadata from
  507. the DB rows.
  508. Args:
  509. events (list[FrozenEvent])
  510. rows (list[_EventDictReturn])
  511. topo_order (bool): Whether the events were ordered topologically
  512. or by stream ordering. If true then all rows should have a non
  513. null topological_ordering.
  514. """
  515. for event, row in zip(events, rows):
  516. stream = row.stream_ordering
  517. if topo_order and row.topological_ordering:
  518. topo = row.topological_ordering
  519. else:
  520. topo = None
  521. internal = event.internal_metadata
  522. internal.before = str(RoomStreamToken(topo, stream - 1))
  523. internal.after = str(RoomStreamToken(topo, stream))
  524. internal.order = (int(topo) if topo else 0, int(stream))
  525. @defer.inlineCallbacks
  526. def get_events_around(
  527. self, room_id, event_id, before_limit, after_limit, event_filter=None
  528. ):
  529. """Retrieve events and pagination tokens around a given event in a
  530. room.
  531. Args:
  532. room_id (str)
  533. event_id (str)
  534. before_limit (int)
  535. after_limit (int)
  536. event_filter (Filter|None)
  537. Returns:
  538. dict
  539. """
  540. results = yield self.db.runInteraction(
  541. "get_events_around",
  542. self._get_events_around_txn,
  543. room_id,
  544. event_id,
  545. before_limit,
  546. after_limit,
  547. event_filter,
  548. )
  549. events_before = yield self.get_events_as_list(
  550. list(results["before"]["event_ids"]), get_prev_content=True
  551. )
  552. events_after = yield self.get_events_as_list(
  553. list(results["after"]["event_ids"]), get_prev_content=True
  554. )
  555. return {
  556. "events_before": events_before,
  557. "events_after": events_after,
  558. "start": results["before"]["token"],
  559. "end": results["after"]["token"],
  560. }
  561. def _get_events_around_txn(
  562. self, txn, room_id, event_id, before_limit, after_limit, event_filter
  563. ):
  564. """Retrieves event_ids and pagination tokens around a given event in a
  565. room.
  566. Args:
  567. room_id (str)
  568. event_id (str)
  569. before_limit (int)
  570. after_limit (int)
  571. event_filter (Filter|None)
  572. Returns:
  573. dict
  574. """
  575. results = self.db.simple_select_one_txn(
  576. txn,
  577. "events",
  578. keyvalues={"event_id": event_id, "room_id": room_id},
  579. retcols=["stream_ordering", "topological_ordering"],
  580. )
  581. # Paginating backwards includes the event at the token, but paginating
  582. # forward doesn't.
  583. before_token = RoomStreamToken(
  584. results["topological_ordering"] - 1, results["stream_ordering"]
  585. )
  586. after_token = RoomStreamToken(
  587. results["topological_ordering"], results["stream_ordering"]
  588. )
  589. rows, start_token = self._paginate_room_events_txn(
  590. txn,
  591. room_id,
  592. before_token,
  593. direction="b",
  594. limit=before_limit,
  595. event_filter=event_filter,
  596. )
  597. events_before = [r.event_id for r in rows]
  598. rows, end_token = self._paginate_room_events_txn(
  599. txn,
  600. room_id,
  601. after_token,
  602. direction="f",
  603. limit=after_limit,
  604. event_filter=event_filter,
  605. )
  606. events_after = [r.event_id for r in rows]
  607. return {
  608. "before": {"event_ids": events_before, "token": start_token},
  609. "after": {"event_ids": events_after, "token": end_token},
  610. }
  611. @defer.inlineCallbacks
  612. def get_all_new_events_stream(self, from_id, current_id, limit):
  613. """Get all new events
  614. Returns all events with from_id < stream_ordering <= current_id.
  615. Args:
  616. from_id (int): the stream_ordering of the last event we processed
  617. current_id (int): the stream_ordering of the most recently processed event
  618. limit (int): the maximum number of events to return
  619. Returns:
  620. Deferred[Tuple[int, list[FrozenEvent]]]: A tuple of (next_id, events), where
  621. `next_id` is the next value to pass as `from_id` (it will either be the
  622. stream_ordering of the last returned event, or, if fewer than `limit` events
  623. were found, `current_id`.
  624. """
  625. def get_all_new_events_stream_txn(txn):
  626. sql = (
  627. "SELECT e.stream_ordering, e.event_id"
  628. " FROM events AS e"
  629. " WHERE"
  630. " ? < e.stream_ordering AND e.stream_ordering <= ?"
  631. " ORDER BY e.stream_ordering ASC"
  632. " LIMIT ?"
  633. )
  634. txn.execute(sql, (from_id, current_id, limit))
  635. rows = txn.fetchall()
  636. upper_bound = current_id
  637. if len(rows) == limit:
  638. upper_bound = rows[-1][0]
  639. return upper_bound, [row[1] for row in rows]
  640. upper_bound, event_ids = yield self.db.runInteraction(
  641. "get_all_new_events_stream", get_all_new_events_stream_txn
  642. )
  643. events = yield self.get_events_as_list(event_ids)
  644. return upper_bound, events
  645. def get_federation_out_pos(self, typ):
  646. return self.db.simple_select_one_onecol(
  647. table="federation_stream_position",
  648. retcol="stream_id",
  649. keyvalues={"type": typ},
  650. desc="get_federation_out_pos",
  651. )
  652. def update_federation_out_pos(self, typ, stream_id):
  653. return self.db.simple_update_one(
  654. table="federation_stream_position",
  655. keyvalues={"type": typ},
  656. updatevalues={"stream_id": stream_id},
  657. desc="update_federation_out_pos",
  658. )
  659. def has_room_changed_since(self, room_id, stream_id):
  660. return self._events_stream_cache.has_entity_changed(room_id, stream_id)
  661. def _paginate_room_events_txn(
  662. self,
  663. txn,
  664. room_id,
  665. from_token,
  666. to_token=None,
  667. direction="b",
  668. limit=-1,
  669. event_filter=None,
  670. ):
  671. """Returns list of events before or after a given token.
  672. Args:
  673. txn
  674. room_id (str)
  675. from_token (RoomStreamToken): The token used to stream from
  676. to_token (RoomStreamToken|None): A token which if given limits the
  677. results to only those before
  678. direction(char): Either 'b' or 'f' to indicate whether we are
  679. paginating forwards or backwards from `from_key`.
  680. limit (int): The maximum number of events to return.
  681. event_filter (Filter|None): If provided filters the events to
  682. those that match the filter.
  683. Returns:
  684. Deferred[tuple[list[_EventDictReturn], str]]: Returns the results
  685. as a list of _EventDictReturn and a token that points to the end
  686. of the result set. If no events are returned then the end of the
  687. stream has been reached (i.e. there are no events between
  688. `from_token` and `to_token`), or `limit` is zero.
  689. """
  690. assert int(limit) >= 0
  691. # Tokens really represent positions between elements, but we use
  692. # the convention of pointing to the event before the gap. Hence
  693. # we have a bit of asymmetry when it comes to equalities.
  694. args = [False, room_id]
  695. if direction == "b":
  696. order = "DESC"
  697. else:
  698. order = "ASC"
  699. bounds = generate_pagination_where_clause(
  700. direction=direction,
  701. column_names=("topological_ordering", "stream_ordering"),
  702. from_token=from_token,
  703. to_token=to_token,
  704. engine=self.database_engine,
  705. )
  706. filter_clause, filter_args = filter_to_clause(event_filter)
  707. if filter_clause:
  708. bounds += " AND " + filter_clause
  709. args.extend(filter_args)
  710. args.append(int(limit))
  711. select_keywords = "SELECT"
  712. join_clause = ""
  713. if event_filter and event_filter.labels:
  714. # If we're not filtering on a label, then joining on event_labels will
  715. # return as many row for a single event as the number of labels it has. To
  716. # avoid this, only join if we're filtering on at least one label.
  717. join_clause = """
  718. LEFT JOIN event_labels
  719. USING (event_id, room_id, topological_ordering)
  720. """
  721. if len(event_filter.labels) > 1:
  722. # Using DISTINCT in this SELECT query is quite expensive, because it
  723. # requires the engine to sort on the entire (not limited) result set,
  724. # i.e. the entire events table. We only need to use it when we're
  725. # filtering on more than two labels, because that's the only scenario
  726. # in which we can possibly to get multiple times the same event ID in
  727. # the results.
  728. select_keywords += "DISTINCT"
  729. sql = """
  730. %(select_keywords)s event_id, topological_ordering, stream_ordering
  731. FROM events
  732. %(join_clause)s
  733. WHERE outlier = ? AND room_id = ? AND %(bounds)s
  734. ORDER BY topological_ordering %(order)s,
  735. stream_ordering %(order)s LIMIT ?
  736. """ % {
  737. "select_keywords": select_keywords,
  738. "join_clause": join_clause,
  739. "bounds": bounds,
  740. "order": order,
  741. }
  742. txn.execute(sql, args)
  743. rows = [_EventDictReturn(row[0], row[1], row[2]) for row in txn]
  744. if rows:
  745. topo = rows[-1].topological_ordering
  746. toke = rows[-1].stream_ordering
  747. if direction == "b":
  748. # Tokens are positions between events.
  749. # This token points *after* the last event in the chunk.
  750. # We need it to point to the event before it in the chunk
  751. # when we are going backwards so we subtract one from the
  752. # stream part.
  753. toke -= 1
  754. next_token = RoomStreamToken(topo, toke)
  755. else:
  756. # TODO (erikj): We should work out what to do here instead.
  757. next_token = to_token if to_token else from_token
  758. return rows, str(next_token)
  759. @defer.inlineCallbacks
  760. def paginate_room_events(
  761. self, room_id, from_key, to_key=None, direction="b", limit=-1, event_filter=None
  762. ):
  763. """Returns list of events before or after a given token.
  764. Args:
  765. room_id (str)
  766. from_key (str): The token used to stream from
  767. to_key (str|None): A token which if given limits the results to
  768. only those before
  769. direction(char): Either 'b' or 'f' to indicate whether we are
  770. paginating forwards or backwards from `from_key`.
  771. limit (int): The maximum number of events to return.
  772. event_filter (Filter|None): If provided filters the events to
  773. those that match the filter.
  774. Returns:
  775. tuple[list[FrozenEvent], str]: Returns the results as a list of
  776. events and a token that points to the end of the result set. If no
  777. events are returned then the end of the stream has been reached
  778. (i.e. there are no events between `from_key` and `to_key`).
  779. """
  780. from_key = RoomStreamToken.parse(from_key)
  781. if to_key:
  782. to_key = RoomStreamToken.parse(to_key)
  783. rows, token = yield self.db.runInteraction(
  784. "paginate_room_events",
  785. self._paginate_room_events_txn,
  786. room_id,
  787. from_key,
  788. to_key,
  789. direction,
  790. limit,
  791. event_filter,
  792. )
  793. events = yield self.get_events_as_list(
  794. [r.event_id for r in rows], get_prev_content=True
  795. )
  796. self._set_before_and_after(events, rows)
  797. return (events, token)
  798. class StreamStore(StreamWorkerStore):
  799. def get_room_max_stream_ordering(self):
  800. return self._stream_id_gen.get_current_token()
  801. def get_room_min_stream_ordering(self):
  802. return self._backfill_id_gen.get_current_token()