state.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # Copyright 2022 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. from typing import TYPE_CHECKING, Tuple
  16. from twisted.web.server import Request
  17. from synapse.api.errors import SynapseError
  18. from synapse.http.server import HttpServer
  19. from synapse.replication.http._base import ReplicationEndpoint
  20. from synapse.types import JsonDict
  21. if TYPE_CHECKING:
  22. from synapse.server import HomeServer
  23. logger = logging.getLogger(__name__)
  24. class ReplicationUpdateCurrentStateRestServlet(ReplicationEndpoint):
  25. """Recalculates the current state for a room, and persists it.
  26. The API looks like:
  27. POST /_synapse/replication/update_current_state/:room_id
  28. {}
  29. 200 OK
  30. {}
  31. """
  32. NAME = "update_current_state"
  33. PATH_ARGS = ("room_id",)
  34. def __init__(self, hs: "HomeServer"):
  35. super().__init__(hs)
  36. self._state_handler = hs.get_state_handler()
  37. self._events_shard_config = hs.config.worker.events_shard_config
  38. self._instance_name = hs.get_instance_name()
  39. @staticmethod
  40. async def _serialize_payload(room_id: str) -> JsonDict: # type: ignore[override]
  41. return {}
  42. async def _handle_request( # type: ignore[override]
  43. self, request: Request, content: JsonDict, room_id: str
  44. ) -> Tuple[int, JsonDict]:
  45. writer_instance = self._events_shard_config.get_instance(room_id)
  46. if writer_instance != self._instance_name:
  47. raise SynapseError(
  48. 400, "/update_current_state request was routed to the wrong worker"
  49. )
  50. await self._state_handler.update_current_state(room_id)
  51. return 200, {}
  52. def register_servlets(hs: "HomeServer", http_server: HttpServer) -> None:
  53. if hs.get_instance_name() in hs.config.worker.writers.events:
  54. ReplicationUpdateCurrentStateRestServlet(hs).register(http_server)