stream.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  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. @defer.inlineCallbacks
  198. def get_room_events_stream_for_room(self, room_id, from_key, to_key, limit=0,
  199. order='DESC'):
  200. # Note: If from_key is None then we return in topological order. This
  201. # is because in that case we're using this as a "get the last few messages
  202. # in a room" function, rather than "get new messages since last sync"
  203. if from_key is not None:
  204. from_id = RoomStreamToken.parse_stream_token(from_key).stream
  205. else:
  206. from_id = None
  207. to_id = RoomStreamToken.parse_stream_token(to_key).stream
  208. if from_key == to_key:
  209. defer.returnValue(([], from_key))
  210. if from_id:
  211. has_changed = yield self._events_stream_cache.has_entity_changed(
  212. room_id, from_id
  213. )
  214. if not has_changed:
  215. defer.returnValue(([], from_key))
  216. def f(txn):
  217. if from_id is not None:
  218. sql = (
  219. "SELECT event_id, stream_ordering FROM events WHERE"
  220. " room_id = ?"
  221. " AND not outlier"
  222. " AND stream_ordering > ? AND stream_ordering <= ?"
  223. " ORDER BY stream_ordering %s LIMIT ?"
  224. ) % (order,)
  225. txn.execute(sql, (room_id, from_id, to_id, limit))
  226. else:
  227. sql = (
  228. "SELECT event_id, stream_ordering FROM events WHERE"
  229. " room_id = ?"
  230. " AND not outlier"
  231. " AND stream_ordering <= ?"
  232. " ORDER BY topological_ordering %s, stream_ordering %s LIMIT ?"
  233. ) % (order, order,)
  234. txn.execute(sql, (room_id, to_id, limit))
  235. rows = self.cursor_to_dict(txn)
  236. return rows
  237. rows = yield self.runInteraction("get_room_events_stream_for_room", f)
  238. ret = yield self._get_events(
  239. [r["event_id"] for r in rows],
  240. get_prev_content=True
  241. )
  242. self._set_before_and_after(ret, rows, topo_order=from_id is None)
  243. if order.lower() == "desc":
  244. ret.reverse()
  245. if rows:
  246. key = "s%d" % min(r["stream_ordering"] for r in rows)
  247. else:
  248. # Assume we didn't get anything because there was nothing to
  249. # get.
  250. key = from_key
  251. defer.returnValue((ret, key))
  252. @defer.inlineCallbacks
  253. def get_membership_changes_for_user(self, user_id, from_key, to_key):
  254. if from_key is not None:
  255. from_id = RoomStreamToken.parse_stream_token(from_key).stream
  256. else:
  257. from_id = None
  258. to_id = RoomStreamToken.parse_stream_token(to_key).stream
  259. if from_key == to_key:
  260. defer.returnValue([])
  261. if from_id:
  262. has_changed = self._membership_stream_cache.has_entity_changed(
  263. user_id, int(from_id)
  264. )
  265. if not has_changed:
  266. defer.returnValue([])
  267. def f(txn):
  268. if from_id is not None:
  269. sql = (
  270. "SELECT m.event_id, stream_ordering FROM events AS e,"
  271. " room_memberships AS m"
  272. " WHERE e.event_id = m.event_id"
  273. " AND m.user_id = ?"
  274. " AND e.stream_ordering > ? AND e.stream_ordering <= ?"
  275. " ORDER BY e.stream_ordering ASC"
  276. )
  277. txn.execute(sql, (user_id, from_id, to_id,))
  278. else:
  279. sql = (
  280. "SELECT m.event_id, stream_ordering FROM events AS e,"
  281. " room_memberships AS m"
  282. " WHERE e.event_id = m.event_id"
  283. " AND m.user_id = ?"
  284. " AND stream_ordering <= ?"
  285. " ORDER BY stream_ordering ASC"
  286. )
  287. txn.execute(sql, (user_id, to_id,))
  288. rows = self.cursor_to_dict(txn)
  289. return rows
  290. rows = yield self.runInteraction("get_membership_changes_for_user", f)
  291. ret = yield self._get_events(
  292. [r["event_id"] for r in rows],
  293. get_prev_content=True
  294. )
  295. self._set_before_and_after(ret, rows, topo_order=False)
  296. defer.returnValue(ret)
  297. @defer.inlineCallbacks
  298. def paginate_room_events(self, room_id, from_key, to_key=None,
  299. direction='b', limit=-1, event_filter=None):
  300. # Tokens really represent positions between elements, but we use
  301. # the convention of pointing to the event before the gap. Hence
  302. # we have a bit of asymmetry when it comes to equalities.
  303. args = [False, room_id]
  304. if direction == 'b':
  305. order = "DESC"
  306. bounds = upper_bound(
  307. RoomStreamToken.parse(from_key), self.database_engine
  308. )
  309. if to_key:
  310. bounds = "%s AND %s" % (bounds, lower_bound(
  311. RoomStreamToken.parse(to_key), self.database_engine
  312. ))
  313. else:
  314. order = "ASC"
  315. bounds = lower_bound(
  316. RoomStreamToken.parse(from_key), self.database_engine
  317. )
  318. if to_key:
  319. bounds = "%s AND %s" % (bounds, upper_bound(
  320. RoomStreamToken.parse(to_key), self.database_engine
  321. ))
  322. filter_clause, filter_args = filter_to_clause(event_filter)
  323. if filter_clause:
  324. bounds += " AND " + filter_clause
  325. args.extend(filter_args)
  326. if int(limit) > 0:
  327. args.append(int(limit))
  328. limit_str = " LIMIT ?"
  329. else:
  330. limit_str = ""
  331. sql = (
  332. "SELECT * FROM events"
  333. " WHERE outlier = ? AND room_id = ? AND %(bounds)s"
  334. " ORDER BY topological_ordering %(order)s,"
  335. " stream_ordering %(order)s %(limit)s"
  336. ) % {
  337. "bounds": bounds,
  338. "order": order,
  339. "limit": limit_str
  340. }
  341. def f(txn):
  342. txn.execute(sql, args)
  343. rows = self.cursor_to_dict(txn)
  344. if rows:
  345. topo = rows[-1]["topological_ordering"]
  346. toke = rows[-1]["stream_ordering"]
  347. if direction == 'b':
  348. # Tokens are positions between events.
  349. # This token points *after* the last event in the chunk.
  350. # We need it to point to the event before it in the chunk
  351. # when we are going backwards so we subtract one from the
  352. # stream part.
  353. toke -= 1
  354. next_token = str(RoomStreamToken(topo, toke))
  355. else:
  356. # TODO (erikj): We should work out what to do here instead.
  357. next_token = to_key if to_key else from_key
  358. return rows, next_token,
  359. rows, token = yield self.runInteraction("paginate_room_events", f)
  360. events = yield self._get_events(
  361. [r["event_id"] for r in rows],
  362. get_prev_content=True
  363. )
  364. self._set_before_and_after(events, rows)
  365. defer.returnValue((events, token))
  366. @defer.inlineCallbacks
  367. def get_recent_events_for_room(self, room_id, limit, end_token, from_token=None):
  368. rows, token = yield self.get_recent_event_ids_for_room(
  369. room_id, limit, end_token, from_token
  370. )
  371. logger.debug("stream before")
  372. events = yield self._get_events(
  373. [r["event_id"] for r in rows],
  374. get_prev_content=True
  375. )
  376. logger.debug("stream after")
  377. self._set_before_and_after(events, rows)
  378. defer.returnValue((events, token))
  379. @cached(num_args=4)
  380. def get_recent_event_ids_for_room(self, room_id, limit, end_token, from_token=None):
  381. end_token = RoomStreamToken.parse_stream_token(end_token)
  382. if from_token is None:
  383. sql = (
  384. "SELECT stream_ordering, topological_ordering, event_id"
  385. " FROM events"
  386. " WHERE room_id = ? AND stream_ordering <= ? AND outlier = ?"
  387. " ORDER BY topological_ordering DESC, stream_ordering DESC"
  388. " LIMIT ?"
  389. )
  390. else:
  391. from_token = RoomStreamToken.parse_stream_token(from_token)
  392. sql = (
  393. "SELECT stream_ordering, topological_ordering, event_id"
  394. " FROM events"
  395. " WHERE room_id = ? AND stream_ordering > ?"
  396. " AND stream_ordering <= ? AND outlier = ?"
  397. " ORDER BY topological_ordering DESC, stream_ordering DESC"
  398. " LIMIT ?"
  399. )
  400. def get_recent_events_for_room_txn(txn):
  401. if from_token is None:
  402. txn.execute(sql, (room_id, end_token.stream, False, limit,))
  403. else:
  404. txn.execute(sql, (
  405. room_id, from_token.stream, end_token.stream, False, limit
  406. ))
  407. rows = self.cursor_to_dict(txn)
  408. rows.reverse() # As we selected with reverse ordering
  409. if rows:
  410. # Tokens are positions between events.
  411. # This token points *after* the last event in the chunk.
  412. # We need it to point to the event before it in the chunk
  413. # since we are going backwards so we subtract one from the
  414. # stream part.
  415. topo = rows[0]["topological_ordering"]
  416. toke = rows[0]["stream_ordering"] - 1
  417. start_token = str(RoomStreamToken(topo, toke))
  418. token = (start_token, str(end_token))
  419. else:
  420. token = (str(end_token), str(end_token))
  421. return rows, token
  422. return self.runInteraction(
  423. "get_recent_events_for_room", get_recent_events_for_room_txn
  424. )
  425. @defer.inlineCallbacks
  426. def get_room_events_max_id(self, room_id=None):
  427. """Returns the current token for rooms stream.
  428. By default, it returns the current global stream token. Specifying a
  429. `room_id` causes it to return the current room specific topological
  430. token.
  431. """
  432. token = yield self._stream_id_gen.get_current_token()
  433. if room_id is None:
  434. defer.returnValue("s%d" % (token,))
  435. else:
  436. topo = yield self.runInteraction(
  437. "_get_max_topological_txn", self._get_max_topological_txn,
  438. room_id,
  439. )
  440. defer.returnValue("t%d-%d" % (topo, token))
  441. def get_room_max_stream_ordering(self):
  442. return self._stream_id_gen.get_current_token()
  443. def get_room_min_stream_ordering(self):
  444. return self._backfill_id_gen.get_current_token()
  445. def get_stream_token_for_event(self, event_id):
  446. """The stream token for an event
  447. Args:
  448. event_id(str): The id of the event to look up a stream token for.
  449. Raises:
  450. StoreError if the event wasn't in the database.
  451. Returns:
  452. A deferred "s%d" stream token.
  453. """
  454. return self._simple_select_one_onecol(
  455. table="events",
  456. keyvalues={"event_id": event_id},
  457. retcol="stream_ordering",
  458. ).addCallback(lambda row: "s%d" % (row,))
  459. def get_topological_token_for_event(self, event_id):
  460. """The stream token for an event
  461. Args:
  462. event_id(str): The id of the event to look up a stream token for.
  463. Raises:
  464. StoreError if the event wasn't in the database.
  465. Returns:
  466. A deferred "t%d-%d" topological token.
  467. """
  468. return self._simple_select_one(
  469. table="events",
  470. keyvalues={"event_id": event_id},
  471. retcols=("stream_ordering", "topological_ordering"),
  472. desc="get_topological_token_for_event",
  473. ).addCallback(lambda row: "t%d-%d" % (
  474. row["topological_ordering"], row["stream_ordering"],)
  475. )
  476. def get_max_topological_token(self, room_id, stream_key):
  477. sql = (
  478. "SELECT max(topological_ordering) FROM events"
  479. " WHERE room_id = ? AND stream_ordering < ?"
  480. )
  481. return self._execute(
  482. "get_max_topological_token", None,
  483. sql, room_id, stream_key,
  484. ).addCallback(
  485. lambda r: r[0][0] if r else 0
  486. )
  487. def _get_max_topological_txn(self, txn, room_id):
  488. txn.execute(
  489. "SELECT MAX(topological_ordering) FROM events"
  490. " WHERE room_id = ?",
  491. (room_id,)
  492. )
  493. rows = txn.fetchall()
  494. return rows[0][0] if rows else 0
  495. @staticmethod
  496. def _set_before_and_after(events, rows, topo_order=True):
  497. for event, row in zip(events, rows):
  498. stream = row["stream_ordering"]
  499. if topo_order:
  500. topo = event.depth
  501. else:
  502. topo = None
  503. internal = event.internal_metadata
  504. internal.before = str(RoomStreamToken(topo, stream - 1))
  505. internal.after = str(RoomStreamToken(topo, stream))
  506. internal.order = (
  507. int(topo) if topo else 0,
  508. int(stream),
  509. )
  510. @defer.inlineCallbacks
  511. def get_events_around(self, room_id, event_id, before_limit, after_limit):
  512. """Retrieve events and pagination tokens around a given event in a
  513. room.
  514. Args:
  515. room_id (str)
  516. event_id (str)
  517. before_limit (int)
  518. after_limit (int)
  519. Returns:
  520. dict
  521. """
  522. results = yield self.runInteraction(
  523. "get_events_around", self._get_events_around_txn,
  524. room_id, event_id, before_limit, after_limit
  525. )
  526. events_before = yield self._get_events(
  527. [e for e in results["before"]["event_ids"]],
  528. get_prev_content=True
  529. )
  530. events_after = yield self._get_events(
  531. [e for e in results["after"]["event_ids"]],
  532. get_prev_content=True
  533. )
  534. defer.returnValue({
  535. "events_before": events_before,
  536. "events_after": events_after,
  537. "start": results["before"]["token"],
  538. "end": results["after"]["token"],
  539. })
  540. def _get_events_around_txn(self, txn, room_id, event_id, before_limit, after_limit):
  541. """Retrieves event_ids and pagination tokens around a given event in a
  542. room.
  543. Args:
  544. room_id (str)
  545. event_id (str)
  546. before_limit (int)
  547. after_limit (int)
  548. Returns:
  549. dict
  550. """
  551. results = self._simple_select_one_txn(
  552. txn,
  553. "events",
  554. keyvalues={
  555. "event_id": event_id,
  556. "room_id": room_id,
  557. },
  558. retcols=["stream_ordering", "topological_ordering"],
  559. )
  560. token = RoomStreamToken(
  561. results["topological_ordering"],
  562. results["stream_ordering"],
  563. )
  564. if isinstance(self.database_engine, Sqlite3Engine):
  565. # SQLite3 doesn't optimise ``(x < a) OR (x = a AND y < b)``
  566. # So we give pass it to SQLite3 as the UNION ALL of the two queries.
  567. query_before = (
  568. "SELECT topological_ordering, stream_ordering, event_id FROM events"
  569. " WHERE room_id = ? AND topological_ordering < ?"
  570. " UNION ALL"
  571. " SELECT topological_ordering, stream_ordering, event_id FROM events"
  572. " WHERE room_id = ? AND topological_ordering = ? AND stream_ordering < ?"
  573. " ORDER BY topological_ordering DESC, stream_ordering DESC LIMIT ?"
  574. )
  575. before_args = (
  576. room_id, token.topological,
  577. room_id, token.topological, token.stream,
  578. before_limit,
  579. )
  580. query_after = (
  581. "SELECT topological_ordering, stream_ordering, event_id FROM events"
  582. " WHERE room_id = ? AND topological_ordering > ?"
  583. " UNION ALL"
  584. " SELECT topological_ordering, stream_ordering, event_id FROM events"
  585. " WHERE room_id = ? AND topological_ordering = ? AND stream_ordering > ?"
  586. " ORDER BY topological_ordering ASC, stream_ordering ASC LIMIT ?"
  587. )
  588. after_args = (
  589. room_id, token.topological,
  590. room_id, token.topological, token.stream,
  591. after_limit,
  592. )
  593. else:
  594. query_before = (
  595. "SELECT topological_ordering, stream_ordering, event_id FROM events"
  596. " WHERE room_id = ? AND %s"
  597. " ORDER BY topological_ordering DESC, stream_ordering DESC LIMIT ?"
  598. ) % (upper_bound(token, self.database_engine, inclusive=False),)
  599. before_args = (room_id, before_limit)
  600. query_after = (
  601. "SELECT topological_ordering, stream_ordering, event_id FROM events"
  602. " WHERE room_id = ? AND %s"
  603. " ORDER BY topological_ordering ASC, stream_ordering ASC LIMIT ?"
  604. ) % (lower_bound(token, self.database_engine, inclusive=False),)
  605. after_args = (room_id, after_limit)
  606. txn.execute(query_before, before_args)
  607. rows = self.cursor_to_dict(txn)
  608. events_before = [r["event_id"] for r in rows]
  609. if rows:
  610. start_token = str(RoomStreamToken(
  611. rows[0]["topological_ordering"],
  612. rows[0]["stream_ordering"] - 1,
  613. ))
  614. else:
  615. start_token = str(RoomStreamToken(
  616. token.topological,
  617. token.stream - 1,
  618. ))
  619. txn.execute(query_after, after_args)
  620. rows = self.cursor_to_dict(txn)
  621. events_after = [r["event_id"] for r in rows]
  622. if rows:
  623. end_token = str(RoomStreamToken(
  624. rows[-1]["topological_ordering"],
  625. rows[-1]["stream_ordering"],
  626. ))
  627. else:
  628. end_token = str(token)
  629. return {
  630. "before": {
  631. "event_ids": events_before,
  632. "token": start_token,
  633. },
  634. "after": {
  635. "event_ids": events_after,
  636. "token": end_token,
  637. },
  638. }
  639. @defer.inlineCallbacks
  640. def get_all_new_events_stream(self, from_id, current_id, limit):
  641. """Get all new events"""
  642. def get_all_new_events_stream_txn(txn):
  643. sql = (
  644. "SELECT e.stream_ordering, e.event_id"
  645. " FROM events AS e"
  646. " WHERE"
  647. " ? < e.stream_ordering AND e.stream_ordering <= ?"
  648. " ORDER BY e.stream_ordering ASC"
  649. " LIMIT ?"
  650. )
  651. txn.execute(sql, (from_id, current_id, limit))
  652. rows = txn.fetchall()
  653. upper_bound = current_id
  654. if len(rows) == limit:
  655. upper_bound = rows[-1][0]
  656. return upper_bound, [row[1] for row in rows]
  657. upper_bound, event_ids = yield self.runInteraction(
  658. "get_all_new_events_stream", get_all_new_events_stream_txn,
  659. )
  660. events = yield self._get_events(event_ids)
  661. defer.returnValue((upper_bound, events))
  662. def get_federation_out_pos(self, typ):
  663. return self._simple_select_one_onecol(
  664. table="federation_stream_position",
  665. retcol="stream_id",
  666. keyvalues={"type": typ},
  667. desc="get_federation_out_pos"
  668. )
  669. def update_federation_out_pos(self, typ, stream_id):
  670. return self._simple_update_one(
  671. table="federation_stream_position",
  672. keyvalues={"type": typ},
  673. updatevalues={"stream_id": stream_id},
  674. desc="update_federation_out_pos",
  675. )