streams.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2020 The Matrix.org Foundation C.I.C.
  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 synapse.api.errors import SynapseError
  17. from synapse.http.servlet import parse_integer
  18. from synapse.replication.http._base import ReplicationEndpoint
  19. logger = logging.getLogger(__name__)
  20. class ReplicationGetStreamUpdates(ReplicationEndpoint):
  21. """Fetches stream updates from a server. Used for streams not persisted to
  22. the database, e.g. typing notifications.
  23. The API looks like:
  24. GET /_synapse/replication/get_repl_stream_updates/<stream name>?from_token=0&to_token=10
  25. 200 OK
  26. {
  27. updates: [ ... ],
  28. upto_token: 10,
  29. limited: False,
  30. }
  31. If there are more rows than can sensibly be returned in one lump, `limited` will be
  32. set to true, and the caller should call again with a new `from_token`.
  33. """
  34. NAME = "get_repl_stream_updates"
  35. PATH_ARGS = ("stream_name",)
  36. METHOD = "GET"
  37. def __init__(self, hs):
  38. super().__init__(hs)
  39. self._instance_name = hs.get_instance_name()
  40. self.streams = hs.get_replication_streams()
  41. @staticmethod
  42. def _serialize_payload(stream_name, from_token, upto_token):
  43. return {"from_token": from_token, "upto_token": upto_token}
  44. async def _handle_request(self, request, stream_name):
  45. stream = self.streams.get(stream_name)
  46. if stream is None:
  47. raise SynapseError(400, "Unknown stream")
  48. from_token = parse_integer(request, "from_token", required=True)
  49. upto_token = parse_integer(request, "upto_token", required=True)
  50. updates, upto_token, limited = await stream.get_updates_since(
  51. self._instance_name, from_token, upto_token
  52. )
  53. return (
  54. 200,
  55. {"updates": updates, "upto_token": upto_token, "limited": limited},
  56. )
  57. def register_servlets(hs, http_server):
  58. ReplicationGetStreamUpdates(hs).register(http_server)