pagination.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. # Copyright 2014 - 2016 OpenMarket Ltd
  2. # Copyright 2017 - 2018 New Vector 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. import logging
  16. from typing import TYPE_CHECKING, List, Optional, Set, Tuple, cast
  17. from twisted.python.failure import Failure
  18. from synapse.api.constants import Direction, EventTypes, Membership
  19. from synapse.api.errors import SynapseError
  20. from synapse.api.filtering import Filter
  21. from synapse.events.utils import SerializeEventConfig
  22. from synapse.handlers.room import ShutdownRoomParams, ShutdownRoomResponse
  23. from synapse.handlers.worker_lock import NEW_EVENT_DURING_PURGE_LOCK_NAME
  24. from synapse.logging.opentracing import trace
  25. from synapse.metrics.background_process_metrics import run_as_background_process
  26. from synapse.rest.admin._base import assert_user_is_admin
  27. from synapse.streams.config import PaginationConfig
  28. from synapse.types import (
  29. JsonDict,
  30. JsonMapping,
  31. Requester,
  32. ScheduledTask,
  33. StreamKeyType,
  34. TaskStatus,
  35. )
  36. from synapse.types.state import StateFilter
  37. from synapse.util.async_helpers import ReadWriteLock
  38. from synapse.visibility import filter_events_for_client
  39. if TYPE_CHECKING:
  40. from synapse.server import HomeServer
  41. logger = logging.getLogger(__name__)
  42. # How many single event gaps we tolerate returning in a `/messages` response before we
  43. # backfill and try to fill in the history. This is an arbitrarily picked number so feel
  44. # free to tune it in the future.
  45. BACKFILL_BECAUSE_TOO_MANY_GAPS_THRESHOLD = 3
  46. # This is used to avoid purging a room several time at the same moment,
  47. # and also paginating during a purge. Pagination can trigger backfill,
  48. # which would create old events locally, and would potentially clash with the room delete.
  49. PURGE_PAGINATION_LOCK_NAME = "purge_pagination_lock"
  50. PURGE_HISTORY_ACTION_NAME = "purge_history"
  51. PURGE_ROOM_ACTION_NAME = "purge_room"
  52. SHUTDOWN_AND_PURGE_ROOM_ACTION_NAME = "shutdown_and_purge_room"
  53. class PaginationHandler:
  54. """Handles pagination and purge history requests.
  55. These are in the same handler due to the fact we need to block clients
  56. paginating during a purge.
  57. """
  58. def __init__(self, hs: "HomeServer"):
  59. self.hs = hs
  60. self.auth = hs.get_auth()
  61. self.store = hs.get_datastores().main
  62. self._storage_controllers = hs.get_storage_controllers()
  63. self._state_storage_controller = self._storage_controllers.state
  64. self.clock = hs.get_clock()
  65. self._server_name = hs.hostname
  66. self._room_shutdown_handler = hs.get_room_shutdown_handler()
  67. self._relations_handler = hs.get_relations_handler()
  68. self._worker_locks = hs.get_worker_locks_handler()
  69. self._task_scheduler = hs.get_task_scheduler()
  70. self.pagination_lock = ReadWriteLock()
  71. # IDs of rooms in which there currently an active purge *or delete* operation.
  72. self._purges_in_progress_by_room: Set[str] = set()
  73. self._event_serializer = hs.get_event_client_serializer()
  74. self._retention_default_max_lifetime = (
  75. hs.config.retention.retention_default_max_lifetime
  76. )
  77. self._retention_allowed_lifetime_min = (
  78. hs.config.retention.retention_allowed_lifetime_min
  79. )
  80. self._retention_allowed_lifetime_max = (
  81. hs.config.retention.retention_allowed_lifetime_max
  82. )
  83. self._forgotten_room_retention_period = (
  84. hs.config.server.forgotten_room_retention_period
  85. )
  86. self._is_master = hs.config.worker.worker_app is None
  87. if hs.config.retention.retention_enabled and self._is_master:
  88. # Run the purge jobs described in the configuration file.
  89. for job in hs.config.retention.retention_purge_jobs:
  90. logger.info("Setting up purge job with config: %s", job)
  91. self.clock.looping_call(
  92. run_as_background_process,
  93. job.interval,
  94. "purge_history_for_rooms_in_range",
  95. self.purge_history_for_rooms_in_range,
  96. job.shortest_max_lifetime,
  97. job.longest_max_lifetime,
  98. )
  99. self._task_scheduler.register_action(
  100. self._purge_history, PURGE_HISTORY_ACTION_NAME
  101. )
  102. self._task_scheduler.register_action(self._purge_room, PURGE_ROOM_ACTION_NAME)
  103. self._task_scheduler.register_action(
  104. self._shutdown_and_purge_room, SHUTDOWN_AND_PURGE_ROOM_ACTION_NAME
  105. )
  106. async def purge_history_for_rooms_in_range(
  107. self, min_ms: Optional[int], max_ms: Optional[int]
  108. ) -> None:
  109. """Purge outdated events from rooms within the given retention range.
  110. If a default retention policy is defined in the server's configuration and its
  111. 'max_lifetime' is within this range, also targets rooms which don't have a
  112. retention policy.
  113. Args:
  114. min_ms: Duration in milliseconds that define the lower limit of
  115. the range to handle (exclusive). If None, it means that the range has no
  116. lower limit.
  117. max_ms: Duration in milliseconds that define the upper limit of
  118. the range to handle (inclusive). If None, it means that the range has no
  119. upper limit.
  120. """
  121. # We want the storage layer to include rooms with no retention policy in its
  122. # return value only if a default retention policy is defined in the server's
  123. # configuration and that policy's 'max_lifetime' is either lower (or equal) than
  124. # max_ms or higher than min_ms (or both).
  125. if self._retention_default_max_lifetime is not None:
  126. include_null = True
  127. if min_ms is not None and min_ms >= self._retention_default_max_lifetime:
  128. # The default max_lifetime is lower than (or equal to) min_ms.
  129. include_null = False
  130. if max_ms is not None and max_ms < self._retention_default_max_lifetime:
  131. # The default max_lifetime is higher than max_ms.
  132. include_null = False
  133. else:
  134. include_null = False
  135. logger.info(
  136. "[purge] Running retention purge job for %s < max_lifetime <= %s (include NULLs = %s)",
  137. min_ms,
  138. max_ms,
  139. include_null,
  140. )
  141. rooms = await self.store.get_rooms_for_retention_period_in_range(
  142. min_ms, max_ms, include_null
  143. )
  144. logger.debug("[purge] Rooms to purge: %s", rooms)
  145. for room_id, retention_policy in rooms.items():
  146. logger.info("[purge] Attempting to purge messages in room %s", room_id)
  147. if len(await self.get_delete_tasks_by_room(room_id, only_active=True)) > 0:
  148. logger.warning(
  149. "[purge] not purging room %s for retention as there's an ongoing purge"
  150. " running for this room",
  151. room_id,
  152. )
  153. continue
  154. # If max_lifetime is None, it means that the room has no retention policy.
  155. # Given we only retrieve such rooms when there's a default retention policy
  156. # defined in the server's configuration, we can safely assume that's the
  157. # case and use it for this room.
  158. max_lifetime = (
  159. retention_policy.max_lifetime or self._retention_default_max_lifetime
  160. )
  161. # Cap the effective max_lifetime to be within the range allowed in the
  162. # config.
  163. # We do this in two steps:
  164. # 1. Make sure it's higher or equal to the minimum allowed value, and if
  165. # it's not replace it with that value. This is because the server
  166. # operator can be required to not delete information before a given
  167. # time, e.g. to comply with freedom of information laws.
  168. # 2. Make sure the resulting value is lower or equal to the maximum allowed
  169. # value, and if it's not replace it with that value. This is because the
  170. # server operator can be required to delete any data after a specific
  171. # amount of time.
  172. if self._retention_allowed_lifetime_min is not None:
  173. max_lifetime = max(self._retention_allowed_lifetime_min, max_lifetime)
  174. if self._retention_allowed_lifetime_max is not None:
  175. max_lifetime = min(max_lifetime, self._retention_allowed_lifetime_max)
  176. logger.debug("[purge] max_lifetime for room %s: %s", room_id, max_lifetime)
  177. # Figure out what token we should start purging at.
  178. ts = self.clock.time_msec() - max_lifetime
  179. stream_ordering = await self.store.find_first_stream_ordering_after_ts(ts)
  180. r = await self.store.get_room_event_before_stream_ordering(
  181. room_id,
  182. stream_ordering,
  183. )
  184. if not r:
  185. logger.warning(
  186. "[purge] purging events not possible: No event found "
  187. "(ts %i => stream_ordering %i)",
  188. ts,
  189. stream_ordering,
  190. )
  191. continue
  192. (stream, topo, _event_id) = r
  193. token = "t%d-%d" % (topo, stream)
  194. logger.info("Starting purging events in room %s", room_id)
  195. # We want to purge everything, including local events, and to run the purge in
  196. # the background so that it's not blocking any other operation apart from
  197. # other purges in the same room.
  198. run_as_background_process(
  199. PURGE_HISTORY_ACTION_NAME,
  200. self.purge_history,
  201. room_id,
  202. token,
  203. True,
  204. )
  205. async def start_purge_history(
  206. self, room_id: str, token: str, delete_local_events: bool = False
  207. ) -> str:
  208. """Start off a history purge on a room.
  209. Args:
  210. room_id: The room to purge from
  211. token: topological token to delete events before
  212. delete_local_events: True to delete local events as well as
  213. remote ones
  214. Returns:
  215. unique ID for this purge transaction.
  216. """
  217. purge_id = await self._task_scheduler.schedule_task(
  218. PURGE_HISTORY_ACTION_NAME,
  219. resource_id=room_id,
  220. params={"token": token, "delete_local_events": delete_local_events},
  221. )
  222. # we log the purge_id here so that it can be tied back to the
  223. # request id in the log lines.
  224. logger.info("[purge] starting purge_id %s", purge_id)
  225. return purge_id
  226. async def _purge_history(
  227. self,
  228. task: ScheduledTask,
  229. ) -> Tuple[TaskStatus, Optional[JsonMapping], Optional[str]]:
  230. """
  231. Scheduler action to purge some history of a room.
  232. """
  233. if (
  234. task.resource_id is None
  235. or task.params is None
  236. or "token" not in task.params
  237. or "delete_local_events" not in task.params
  238. ):
  239. return (
  240. TaskStatus.FAILED,
  241. None,
  242. "Not enough parameters passed to _purge_history",
  243. )
  244. err = await self.purge_history(
  245. task.resource_id,
  246. task.params["token"],
  247. task.params["delete_local_events"],
  248. )
  249. if err is not None:
  250. return TaskStatus.FAILED, None, err
  251. return TaskStatus.COMPLETE, None, None
  252. async def purge_history(
  253. self,
  254. room_id: str,
  255. token: str,
  256. delete_local_events: bool,
  257. ) -> Optional[str]:
  258. """Carry out a history purge on a room.
  259. Args:
  260. room_id: The room to purge from
  261. token: topological token to delete events before
  262. delete_local_events: True to delete local events as well as remote ones
  263. """
  264. try:
  265. async with self._worker_locks.acquire_read_write_lock(
  266. PURGE_PAGINATION_LOCK_NAME, room_id, write=True
  267. ):
  268. await self._storage_controllers.purge_events.purge_history(
  269. room_id, token, delete_local_events
  270. )
  271. logger.info("[purge] complete")
  272. return None
  273. except Exception:
  274. f = Failure()
  275. logger.error(
  276. "[purge] failed", exc_info=(f.type, f.value, f.getTracebackObject())
  277. )
  278. return f.getErrorMessage()
  279. async def get_delete_task(self, delete_id: str) -> Optional[ScheduledTask]:
  280. """Get the current status of an active deleting
  281. Args:
  282. delete_id: delete_id returned by start_shutdown_and_purge_room
  283. or start_purge_history.
  284. """
  285. return await self._task_scheduler.get_task(delete_id)
  286. async def get_delete_tasks_by_room(
  287. self, room_id: str, only_active: Optional[bool] = False
  288. ) -> List[ScheduledTask]:
  289. """Get complete, failed or active delete tasks by room
  290. Args:
  291. room_id: room_id that is deleted
  292. only_active: if True, completed&failed tasks will be omitted
  293. """
  294. statuses = [TaskStatus.ACTIVE]
  295. if not only_active:
  296. statuses += [TaskStatus.COMPLETE, TaskStatus.FAILED]
  297. return await self._task_scheduler.get_tasks(
  298. actions=[PURGE_ROOM_ACTION_NAME, SHUTDOWN_AND_PURGE_ROOM_ACTION_NAME],
  299. resource_id=room_id,
  300. statuses=statuses,
  301. )
  302. async def _purge_room(
  303. self,
  304. task: ScheduledTask,
  305. ) -> Tuple[TaskStatus, Optional[JsonMapping], Optional[str]]:
  306. """
  307. Scheduler action to purge a room.
  308. """
  309. if not task.resource_id:
  310. raise Exception("No room id passed to purge_room task")
  311. params = task.params if task.params else {}
  312. await self.purge_room(task.resource_id, params.get("force", False))
  313. return TaskStatus.COMPLETE, None, None
  314. async def purge_room(
  315. self,
  316. room_id: str,
  317. force: bool,
  318. ) -> None:
  319. """Purge the given room from the database.
  320. Args:
  321. room_id: room to be purged
  322. force: set true to skip checking for joined users.
  323. """
  324. logger.info("starting purge room_id=%s force=%s", room_id, force)
  325. async with self._worker_locks.acquire_multi_read_write_lock(
  326. [
  327. (PURGE_PAGINATION_LOCK_NAME, room_id),
  328. (NEW_EVENT_DURING_PURGE_LOCK_NAME, room_id),
  329. ],
  330. write=True,
  331. ):
  332. # first check that we have no users in this room
  333. joined = await self.store.is_host_joined(room_id, self._server_name)
  334. if joined:
  335. if force:
  336. logger.info(
  337. "force-purging room %s with some local users still joined",
  338. room_id,
  339. )
  340. else:
  341. raise SynapseError(400, "Users are still joined to this room")
  342. await self._storage_controllers.purge_events.purge_room(room_id)
  343. logger.info("purge complete for room_id %s", room_id)
  344. @trace
  345. async def get_messages(
  346. self,
  347. requester: Requester,
  348. room_id: str,
  349. pagin_config: PaginationConfig,
  350. as_client_event: bool = True,
  351. event_filter: Optional[Filter] = None,
  352. use_admin_priviledge: bool = False,
  353. ) -> JsonDict:
  354. """Get messages in a room.
  355. Args:
  356. requester: The user requesting messages.
  357. room_id: The room they want messages from.
  358. pagin_config: The pagination config rules to apply, if any.
  359. as_client_event: True to get events in client-server format.
  360. event_filter: Filter to apply to results or None
  361. use_admin_priviledge: if `True`, return all events, regardless
  362. of whether `user` has access to them. To be used **ONLY**
  363. from the admin API.
  364. Returns:
  365. Pagination API results
  366. """
  367. if use_admin_priviledge:
  368. await assert_user_is_admin(self.auth, requester)
  369. user_id = requester.user.to_string()
  370. if pagin_config.from_token:
  371. from_token = pagin_config.from_token
  372. elif pagin_config.direction == Direction.FORWARDS:
  373. from_token = (
  374. await self.hs.get_event_sources().get_start_token_for_pagination(
  375. room_id
  376. )
  377. )
  378. else:
  379. from_token = (
  380. await self.hs.get_event_sources().get_current_token_for_pagination(
  381. room_id
  382. )
  383. )
  384. # We expect `/messages` to use historic pagination tokens by default but
  385. # `/messages` should still works with live tokens when manually provided.
  386. assert from_token.room_key.topological is not None
  387. room_token = from_token.room_key
  388. (membership, member_event_id) = (None, None)
  389. if not use_admin_priviledge:
  390. (
  391. membership,
  392. member_event_id,
  393. ) = await self.auth.check_user_in_room_or_world_readable(
  394. room_id, requester, allow_departed_users=True
  395. )
  396. if pagin_config.direction == Direction.BACKWARDS:
  397. # if we're going backwards, we might need to backfill. This
  398. # requires that we have a topo token.
  399. if room_token.topological:
  400. curr_topo = room_token.topological
  401. else:
  402. curr_topo = await self.store.get_current_topological_token(
  403. room_id, room_token.stream
  404. )
  405. # If they have left the room then clamp the token to be before
  406. # they left the room, to save the effort of loading from the
  407. # database.
  408. if (
  409. pagin_config.direction == Direction.BACKWARDS
  410. and not use_admin_priviledge
  411. and membership == Membership.LEAVE
  412. ):
  413. # This is only None if the room is world_readable, in which case
  414. # "Membership.JOIN" would have been returned and we should never hit
  415. # this branch.
  416. assert member_event_id
  417. leave_token = await self.store.get_topological_token_for_event(
  418. member_event_id
  419. )
  420. assert leave_token.topological is not None
  421. if leave_token.topological < curr_topo:
  422. from_token = from_token.copy_and_replace(
  423. StreamKeyType.ROOM, leave_token
  424. )
  425. to_room_key = None
  426. if pagin_config.to_token:
  427. to_room_key = pagin_config.to_token.room_key
  428. # Initially fetch the events from the database. With any luck, we can return
  429. # these without blocking on backfill (handled below).
  430. events, next_key = await self.store.paginate_room_events(
  431. room_id=room_id,
  432. from_key=from_token.room_key,
  433. to_key=to_room_key,
  434. direction=pagin_config.direction,
  435. limit=pagin_config.limit,
  436. event_filter=event_filter,
  437. )
  438. if pagin_config.direction == Direction.BACKWARDS:
  439. # We use a `Set` because there can be multiple events at a given depth
  440. # and we only care about looking at the unique continum of depths to
  441. # find gaps.
  442. event_depths: Set[int] = {event.depth for event in events}
  443. sorted_event_depths = sorted(event_depths)
  444. # Inspect the depths of the returned events to see if there are any gaps
  445. found_big_gap = False
  446. number_of_gaps = 0
  447. previous_event_depth = (
  448. sorted_event_depths[0] if len(sorted_event_depths) > 0 else 0
  449. )
  450. for event_depth in sorted_event_depths:
  451. # We don't expect a negative depth but we'll just deal with it in
  452. # any case by taking the absolute value to get the true gap between
  453. # any two integers.
  454. depth_gap = abs(event_depth - previous_event_depth)
  455. # A `depth_gap` of 1 is a normal continuous chain to the next event
  456. # (1 <-- 2 <-- 3) so anything larger indicates a missing event (it's
  457. # also possible there is no event at a given depth but we can't ever
  458. # know that for sure)
  459. if depth_gap > 1:
  460. number_of_gaps += 1
  461. # We only tolerate a small number single-event long gaps in the
  462. # returned events because those are most likely just events we've
  463. # failed to pull in the past. Anything longer than that is probably
  464. # a sign that we're missing a decent chunk of history and we should
  465. # try to backfill it.
  466. #
  467. # XXX: It's possible we could tolerate longer gaps if we checked
  468. # that a given events `prev_events` is one that has failed pull
  469. # attempts and we could just treat it like a dead branch of history
  470. # for now or at least something that we don't need the block the
  471. # client on to try pulling.
  472. #
  473. # XXX: If we had something like MSC3871 to indicate gaps in the
  474. # timeline to the client, we could also get away with any sized gap
  475. # and just have the client refetch the holes as they see fit.
  476. if depth_gap > 2:
  477. found_big_gap = True
  478. break
  479. previous_event_depth = event_depth
  480. # Backfill in the foreground if we found a big gap, have too many holes,
  481. # or we don't have enough events to fill the limit that the client asked
  482. # for.
  483. missing_too_many_events = (
  484. number_of_gaps > BACKFILL_BECAUSE_TOO_MANY_GAPS_THRESHOLD
  485. )
  486. not_enough_events_to_fill_response = len(events) < pagin_config.limit
  487. if (
  488. found_big_gap
  489. or missing_too_many_events
  490. or not_enough_events_to_fill_response
  491. ):
  492. did_backfill = await self.hs.get_federation_handler().maybe_backfill(
  493. room_id,
  494. curr_topo,
  495. limit=pagin_config.limit,
  496. )
  497. # If we did backfill something, refetch the events from the database to
  498. # catch anything new that might have been added since we last fetched.
  499. if did_backfill:
  500. events, next_key = await self.store.paginate_room_events(
  501. room_id=room_id,
  502. from_key=from_token.room_key,
  503. to_key=to_room_key,
  504. direction=pagin_config.direction,
  505. limit=pagin_config.limit,
  506. event_filter=event_filter,
  507. )
  508. else:
  509. # Otherwise, we can backfill in the background for eventual
  510. # consistency's sake but we don't need to block the client waiting
  511. # for a costly federation call and processing.
  512. run_as_background_process(
  513. "maybe_backfill_in_the_background",
  514. self.hs.get_federation_handler().maybe_backfill,
  515. room_id,
  516. curr_topo,
  517. limit=pagin_config.limit,
  518. )
  519. next_token = from_token.copy_and_replace(StreamKeyType.ROOM, next_key)
  520. # if no events are returned from pagination, that implies
  521. # we have reached the end of the available events.
  522. # In that case we do not return end, to tell the client
  523. # there is no need for further queries.
  524. if not events:
  525. return {
  526. "chunk": [],
  527. "start": await from_token.to_string(self.store),
  528. }
  529. if event_filter:
  530. events = await event_filter.filter(events)
  531. if not use_admin_priviledge:
  532. events = await filter_events_for_client(
  533. self._storage_controllers,
  534. user_id,
  535. events,
  536. is_peeking=(member_event_id is None),
  537. )
  538. # if after the filter applied there are no more events
  539. # return immediately - but there might be more in next_token batch
  540. if not events:
  541. return {
  542. "chunk": [],
  543. "start": await from_token.to_string(self.store),
  544. "end": await next_token.to_string(self.store),
  545. }
  546. state = None
  547. if event_filter and event_filter.lazy_load_members and len(events) > 0:
  548. # TODO: remove redundant members
  549. # FIXME: we also care about invite targets etc.
  550. state_filter = StateFilter.from_types(
  551. (EventTypes.Member, event.sender) for event in events
  552. )
  553. state_ids = await self._state_storage_controller.get_state_ids_for_event(
  554. events[0].event_id, state_filter=state_filter
  555. )
  556. if state_ids:
  557. state_dict = await self.store.get_events(list(state_ids.values()))
  558. state = state_dict.values()
  559. aggregations = await self._relations_handler.get_bundled_aggregations(
  560. events, user_id
  561. )
  562. time_now = self.clock.time_msec()
  563. serialize_options = SerializeEventConfig(
  564. as_client_event=as_client_event, requester=requester
  565. )
  566. chunk = {
  567. "chunk": (
  568. await self._event_serializer.serialize_events(
  569. events,
  570. time_now,
  571. config=serialize_options,
  572. bundle_aggregations=aggregations,
  573. )
  574. ),
  575. "start": await from_token.to_string(self.store),
  576. "end": await next_token.to_string(self.store),
  577. }
  578. if state:
  579. chunk["state"] = await self._event_serializer.serialize_events(
  580. state, time_now, config=serialize_options
  581. )
  582. return chunk
  583. async def _shutdown_and_purge_room(
  584. self,
  585. task: ScheduledTask,
  586. ) -> Tuple[TaskStatus, Optional[JsonMapping], Optional[str]]:
  587. """
  588. Scheduler action to shutdown and purge a room.
  589. """
  590. if task.resource_id is None or task.params is None:
  591. raise Exception(
  592. "No room id and/or no parameters passed to shutdown_and_purge_room task"
  593. )
  594. room_id = task.resource_id
  595. async def update_result(result: Optional[JsonMapping]) -> None:
  596. await self._task_scheduler.update_task(task.id, result=result)
  597. shutdown_result = (
  598. cast(ShutdownRoomResponse, task.result) if task.result else None
  599. )
  600. shutdown_result = await self._room_shutdown_handler.shutdown_room(
  601. room_id,
  602. cast(ShutdownRoomParams, task.params),
  603. shutdown_result,
  604. update_result,
  605. )
  606. if task.params.get("purge", False):
  607. await self.purge_room(
  608. room_id,
  609. task.params.get("force_purge", False),
  610. )
  611. return (TaskStatus.COMPLETE, shutdown_result, None)
  612. async def start_shutdown_and_purge_room(
  613. self,
  614. room_id: str,
  615. shutdown_params: ShutdownRoomParams,
  616. ) -> str:
  617. """Start off shut down and purge on a room.
  618. Args:
  619. room_id: The ID of the room to shut down.
  620. shutdown_params: parameters for the shutdown
  621. Returns:
  622. unique ID for this delete transaction.
  623. """
  624. if len(await self.get_delete_tasks_by_room(room_id, only_active=True)) > 0:
  625. raise SynapseError(400, "Purge already in progress for %s" % (room_id,))
  626. # This check is double to `RoomShutdownHandler.shutdown_room`
  627. # But here the requester get a direct response / error with HTTP request
  628. # and do not have to check the purge status
  629. new_room_user_id = shutdown_params["new_room_user_id"]
  630. if new_room_user_id is not None:
  631. if not self.hs.is_mine_id(new_room_user_id):
  632. raise SynapseError(
  633. 400, "User must be our own: %s" % (new_room_user_id,)
  634. )
  635. delete_id = await self._task_scheduler.schedule_task(
  636. SHUTDOWN_AND_PURGE_ROOM_ACTION_NAME,
  637. resource_id=room_id,
  638. params=shutdown_params,
  639. )
  640. # we log the delete_id here so that it can be tied back to the
  641. # request id in the log lines.
  642. logger.info(
  643. "starting shutdown room_id %s with delete_id %s",
  644. room_id,
  645. delete_id,
  646. )
  647. return delete_id