stream.py 37 KB

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