room_batch.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. import logging
  2. from typing import TYPE_CHECKING, List, Tuple
  3. from synapse.api.constants import EventContentFields, EventTypes
  4. from synapse.appservice import ApplicationService
  5. from synapse.http.servlet import assert_params_in_dict
  6. from synapse.types import JsonDict, Requester, UserID, create_requester
  7. from synapse.util.stringutils import random_string
  8. if TYPE_CHECKING:
  9. from synapse.server import HomeServer
  10. logger = logging.getLogger(__name__)
  11. class RoomBatchHandler:
  12. def __init__(self, hs: "HomeServer"):
  13. self.hs = hs
  14. self.store = hs.get_datastores().main
  15. self.state_store = hs.get_storage().state
  16. self.event_creation_handler = hs.get_event_creation_handler()
  17. self.room_member_handler = hs.get_room_member_handler()
  18. self.auth = hs.get_auth()
  19. async def inherit_depth_from_prev_ids(self, prev_event_ids: List[str]) -> int:
  20. """Finds the depth which would sort it after the most-recent
  21. prev_event_id but before the successors of those events. If no
  22. successors are found, we assume it's an historical extremity part of the
  23. current batch and use the same depth of the prev_event_ids.
  24. Args:
  25. prev_event_ids: List of prev event IDs
  26. Returns:
  27. Inherited depth
  28. """
  29. (
  30. most_recent_prev_event_id,
  31. most_recent_prev_event_depth,
  32. ) = await self.store.get_max_depth_of(prev_event_ids)
  33. # We want to insert the historical event after the `prev_event` but before the successor event
  34. #
  35. # We inherit depth from the successor event instead of the `prev_event`
  36. # because events returned from `/messages` are first sorted by `topological_ordering`
  37. # which is just the `depth` and then tie-break with `stream_ordering`.
  38. #
  39. # We mark these inserted historical events as "backfilled" which gives them a
  40. # negative `stream_ordering`. If we use the same depth as the `prev_event`,
  41. # then our historical event will tie-break and be sorted before the `prev_event`
  42. # when it should come after.
  43. #
  44. # We want to use the successor event depth so they appear after `prev_event` because
  45. # it has a larger `depth` but before the successor event because the `stream_ordering`
  46. # is negative before the successor event.
  47. successor_event_ids = await self.store.get_successor_events(
  48. most_recent_prev_event_id
  49. )
  50. # If we can't find any successor events, then it's a forward extremity of
  51. # historical messages and we can just inherit from the previous historical
  52. # event which we can already assume has the correct depth where we want
  53. # to insert into.
  54. if not successor_event_ids:
  55. depth = most_recent_prev_event_depth
  56. else:
  57. (
  58. _,
  59. oldest_successor_depth,
  60. ) = await self.store.get_min_depth_of(successor_event_ids)
  61. depth = oldest_successor_depth
  62. return depth
  63. def create_insertion_event_dict(
  64. self, sender: str, room_id: str, origin_server_ts: int
  65. ) -> JsonDict:
  66. """Creates an event dict for an "insertion" event with the proper fields
  67. and a random batch ID.
  68. Args:
  69. sender: The event author MXID
  70. room_id: The room ID that the event belongs to
  71. origin_server_ts: Timestamp when the event was sent
  72. Returns:
  73. The new event dictionary to insert.
  74. """
  75. next_batch_id = random_string(8)
  76. insertion_event = {
  77. "type": EventTypes.MSC2716_INSERTION,
  78. "sender": sender,
  79. "room_id": room_id,
  80. "content": {
  81. EventContentFields.MSC2716_NEXT_BATCH_ID: next_batch_id,
  82. EventContentFields.MSC2716_HISTORICAL: True,
  83. },
  84. "origin_server_ts": origin_server_ts,
  85. }
  86. return insertion_event
  87. async def create_requester_for_user_id_from_app_service(
  88. self, user_id: str, app_service: ApplicationService
  89. ) -> Requester:
  90. """Creates a new requester for the given user_id
  91. and validates that the app service is allowed to control
  92. the given user.
  93. Args:
  94. user_id: The author MXID that the app service is controlling
  95. app_service: The app service that controls the user
  96. Returns:
  97. Requester object
  98. """
  99. await self.auth.validate_appservice_can_control_user_id(app_service, user_id)
  100. return create_requester(user_id, app_service=app_service)
  101. async def get_most_recent_full_state_ids_from_event_id_list(
  102. self, event_ids: List[str]
  103. ) -> List[str]:
  104. """Find the most recent event_id and grab the full state at that event.
  105. We will use this as a base to auth our historical messages against.
  106. Args:
  107. event_ids: List of event ID's to look at
  108. Returns:
  109. List of event ID's
  110. """
  111. (
  112. most_recent_event_id,
  113. _,
  114. ) = await self.store.get_max_depth_of(event_ids)
  115. # mapping from (type, state_key) -> state_event_id
  116. prev_state_map = await self.state_store.get_state_ids_for_event(
  117. most_recent_event_id
  118. )
  119. # List of state event ID's
  120. full_state_ids = list(prev_state_map.values())
  121. return full_state_ids
  122. async def persist_state_events_at_start(
  123. self,
  124. state_events_at_start: List[JsonDict],
  125. room_id: str,
  126. initial_state_event_ids: List[str],
  127. app_service_requester: Requester,
  128. ) -> List[str]:
  129. """Takes all `state_events_at_start` event dictionaries and creates/persists
  130. them in a floating state event chain which don't resolve into the current room
  131. state. They are floating because they reference no prev_events which disconnects
  132. them from the normal DAG.
  133. Args:
  134. state_events_at_start:
  135. room_id: Room where you want the events persisted in.
  136. initial_state_event_ids:
  137. The base set of state for the historical batch which the floating
  138. state chain will derive from. This should probably be the state
  139. from the `prev_event` defined by `/batch_send?prev_event_id=$abc`.
  140. app_service_requester: The requester of an application service.
  141. Returns:
  142. List of state event ID's we just persisted
  143. """
  144. assert app_service_requester.app_service
  145. state_event_ids_at_start = []
  146. state_event_ids = initial_state_event_ids.copy()
  147. # Make the state events float off on their own by specifying no
  148. # prev_events for the first one in the chain so we don't have a bunch of
  149. # `@mxid joined the room` noise between each batch.
  150. prev_event_ids_for_state_chain: List[str] = []
  151. for index, state_event in enumerate(state_events_at_start):
  152. assert_params_in_dict(
  153. state_event, ["type", "origin_server_ts", "content", "sender"]
  154. )
  155. logger.debug(
  156. "RoomBatchSendEventRestServlet inserting state_event=%s", state_event
  157. )
  158. event_dict = {
  159. "type": state_event["type"],
  160. "origin_server_ts": state_event["origin_server_ts"],
  161. "content": state_event["content"],
  162. "room_id": room_id,
  163. "sender": state_event["sender"],
  164. "state_key": state_event["state_key"],
  165. }
  166. # Mark all events as historical
  167. event_dict["content"][EventContentFields.MSC2716_HISTORICAL] = True
  168. # TODO: This is pretty much the same as some other code to handle inserting state in this file
  169. if event_dict["type"] == EventTypes.Member:
  170. membership = event_dict["content"].get("membership", None)
  171. event_id, _ = await self.room_member_handler.update_membership(
  172. await self.create_requester_for_user_id_from_app_service(
  173. state_event["sender"], app_service_requester.app_service
  174. ),
  175. target=UserID.from_string(event_dict["state_key"]),
  176. room_id=room_id,
  177. action=membership,
  178. content=event_dict["content"],
  179. historical=True,
  180. # Only the first event in the state chain should be floating.
  181. # The rest should hang off each other in a chain.
  182. allow_no_prev_events=index == 0,
  183. prev_event_ids=prev_event_ids_for_state_chain,
  184. # The first event in the state chain is floating with no
  185. # `prev_events` which means it can't derive state from
  186. # anywhere automatically. So we need to set some state
  187. # explicitly.
  188. #
  189. # Make sure to use a copy of this list because we modify it
  190. # later in the loop here. Otherwise it will be the same
  191. # reference and also update in the event when we append
  192. # later.
  193. state_event_ids=state_event_ids.copy(),
  194. )
  195. else:
  196. (
  197. event,
  198. _,
  199. ) = await self.event_creation_handler.create_and_send_nonmember_event(
  200. await self.create_requester_for_user_id_from_app_service(
  201. state_event["sender"], app_service_requester.app_service
  202. ),
  203. event_dict,
  204. historical=True,
  205. # Only the first event in the state chain should be floating.
  206. # The rest should hang off each other in a chain.
  207. allow_no_prev_events=index == 0,
  208. prev_event_ids=prev_event_ids_for_state_chain,
  209. # The first event in the state chain is floating with no
  210. # `prev_events` which means it can't derive state from
  211. # anywhere automatically. So we need to set some state
  212. # explicitly.
  213. #
  214. # Make sure to use a copy of this list because we modify it
  215. # later in the loop here. Otherwise it will be the same
  216. # reference and also update in the event when we append later.
  217. state_event_ids=state_event_ids.copy(),
  218. )
  219. event_id = event.event_id
  220. state_event_ids_at_start.append(event_id)
  221. state_event_ids.append(event_id)
  222. # Connect all the state in a floating chain
  223. prev_event_ids_for_state_chain = [event_id]
  224. return state_event_ids_at_start
  225. async def persist_historical_events(
  226. self,
  227. events_to_create: List[JsonDict],
  228. room_id: str,
  229. inherited_depth: int,
  230. initial_state_event_ids: List[str],
  231. app_service_requester: Requester,
  232. ) -> List[str]:
  233. """Create and persists all events provided sequentially. Handles the
  234. complexity of creating events in chronological order so they can
  235. reference each other by prev_event but still persists in
  236. reverse-chronoloical order so they have the correct
  237. (topological_ordering, stream_ordering) and sort correctly from
  238. /messages.
  239. Args:
  240. events_to_create: List of historical events to create in JSON
  241. dictionary format.
  242. room_id: Room where you want the events persisted in.
  243. inherited_depth: The depth to create the events at (you will
  244. probably by calling inherit_depth_from_prev_ids(...)).
  245. initial_state_event_ids:
  246. This is used to set explicit state for the insertion event at
  247. the start of the historical batch since it's floating with no
  248. prev_events to derive state from automatically.
  249. app_service_requester: The requester of an application service.
  250. Returns:
  251. List of persisted event IDs
  252. """
  253. assert app_service_requester.app_service
  254. # We expect the first event in a historical batch to be an insertion event
  255. assert events_to_create[0]["type"] == EventTypes.MSC2716_INSERTION
  256. # We expect the last event in a historical batch to be an batch event
  257. assert events_to_create[-1]["type"] == EventTypes.MSC2716_BATCH
  258. # Make the historical event chain float off on its own by specifying no
  259. # prev_events for the first event in the chain which causes the HS to
  260. # ask for the state at the start of the batch later.
  261. prev_event_ids: List[str] = []
  262. event_ids = []
  263. events_to_persist = []
  264. for index, ev in enumerate(events_to_create):
  265. assert_params_in_dict(ev, ["type", "origin_server_ts", "content", "sender"])
  266. assert self.hs.is_mine_id(ev["sender"]), "User must be our own: %s" % (
  267. ev["sender"],
  268. )
  269. event_dict = {
  270. "type": ev["type"],
  271. "origin_server_ts": ev["origin_server_ts"],
  272. "content": ev["content"],
  273. "room_id": room_id,
  274. "sender": ev["sender"], # requester.user.to_string(),
  275. "prev_events": prev_event_ids.copy(),
  276. }
  277. # Mark all events as historical
  278. event_dict["content"][EventContentFields.MSC2716_HISTORICAL] = True
  279. event, context = await self.event_creation_handler.create_event(
  280. await self.create_requester_for_user_id_from_app_service(
  281. ev["sender"], app_service_requester.app_service
  282. ),
  283. event_dict,
  284. # Only the first event (which is the insertion event) in the
  285. # chain should be floating. The rest should hang off each other
  286. # in a chain.
  287. allow_no_prev_events=index == 0,
  288. prev_event_ids=event_dict.get("prev_events"),
  289. # Since the first event (which is the insertion event) in the
  290. # chain is floating with no `prev_events`, it can't derive state
  291. # from anywhere automatically. So we need to set some state
  292. # explicitly.
  293. state_event_ids=initial_state_event_ids if index == 0 else None,
  294. historical=True,
  295. depth=inherited_depth,
  296. )
  297. assert context._state_group
  298. # Normally this is done when persisting the event but we have to
  299. # pre-emptively do it here because we create all the events first,
  300. # then persist them in another pass below. And we want to share
  301. # state_groups across the whole batch so this lookup needs to work
  302. # for the next event in the batch in this loop.
  303. await self.store.store_state_group_id_for_event_id(
  304. event_id=event.event_id,
  305. state_group_id=context._state_group,
  306. )
  307. logger.debug(
  308. "RoomBatchSendEventRestServlet inserting event=%s, prev_event_ids=%s",
  309. event,
  310. prev_event_ids,
  311. )
  312. events_to_persist.append((event, context))
  313. event_id = event.event_id
  314. event_ids.append(event_id)
  315. prev_event_ids = [event_id]
  316. # Persist events in reverse-chronological order so they have the
  317. # correct stream_ordering as they are backfilled (which decrements).
  318. # Events are sorted by (topological_ordering, stream_ordering)
  319. # where topological_ordering is just depth.
  320. for (event, context) in reversed(events_to_persist):
  321. await self.event_creation_handler.handle_new_client_event(
  322. await self.create_requester_for_user_id_from_app_service(
  323. event.sender, app_service_requester.app_service
  324. ),
  325. event=event,
  326. context=context,
  327. )
  328. return event_ids
  329. async def handle_batch_of_events(
  330. self,
  331. events_to_create: List[JsonDict],
  332. room_id: str,
  333. batch_id_to_connect_to: str,
  334. inherited_depth: int,
  335. initial_state_event_ids: List[str],
  336. app_service_requester: Requester,
  337. ) -> Tuple[List[str], str]:
  338. """
  339. Handles creating and persisting all of the historical events as well as
  340. insertion and batch meta events to make the batch navigable in the DAG.
  341. Args:
  342. events_to_create: List of historical events to create in JSON
  343. dictionary format.
  344. room_id: Room where you want the events created in.
  345. batch_id_to_connect_to: The batch_id from the insertion event you
  346. want this batch to connect to.
  347. inherited_depth: The depth to create the events at (you will
  348. probably by calling inherit_depth_from_prev_ids(...)).
  349. initial_state_event_ids:
  350. This is used to set explicit state for the insertion event at
  351. the start of the historical batch since it's floating with no
  352. prev_events to derive state from automatically. This should
  353. probably be the state from the `prev_event` defined by
  354. `/batch_send?prev_event_id=$abc` plus the outcome of
  355. `persist_state_events_at_start`
  356. app_service_requester: The requester of an application service.
  357. Returns:
  358. Tuple containing a list of created events and the next_batch_id
  359. """
  360. # Connect this current batch to the insertion event from the previous batch
  361. last_event_in_batch = events_to_create[-1]
  362. batch_event = {
  363. "type": EventTypes.MSC2716_BATCH,
  364. "sender": app_service_requester.user.to_string(),
  365. "room_id": room_id,
  366. "content": {
  367. EventContentFields.MSC2716_BATCH_ID: batch_id_to_connect_to,
  368. EventContentFields.MSC2716_HISTORICAL: True,
  369. },
  370. # Since the batch event is put at the end of the batch,
  371. # where the newest-in-time event is, copy the origin_server_ts from
  372. # the last event we're inserting
  373. "origin_server_ts": last_event_in_batch["origin_server_ts"],
  374. }
  375. # Add the batch event to the end of the batch (newest-in-time)
  376. events_to_create.append(batch_event)
  377. # Add an "insertion" event to the start of each batch (next to the oldest-in-time
  378. # event in the batch) so the next batch can be connected to this one.
  379. insertion_event = self.create_insertion_event_dict(
  380. sender=app_service_requester.user.to_string(),
  381. room_id=room_id,
  382. # Since the insertion event is put at the start of the batch,
  383. # where the oldest-in-time event is, copy the origin_server_ts from
  384. # the first event we're inserting
  385. origin_server_ts=events_to_create[0]["origin_server_ts"],
  386. )
  387. next_batch_id = insertion_event["content"][
  388. EventContentFields.MSC2716_NEXT_BATCH_ID
  389. ]
  390. # Prepend the insertion event to the start of the batch (oldest-in-time)
  391. events_to_create = [insertion_event] + events_to_create
  392. # Create and persist all of the historical events
  393. event_ids = await self.persist_historical_events(
  394. events_to_create=events_to_create,
  395. room_id=room_id,
  396. inherited_depth=inherited_depth,
  397. initial_state_event_ids=initial_state_event_ids,
  398. app_service_requester=app_service_requester,
  399. )
  400. return event_ids, next_batch_id