You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

465 lines
20 KiB

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