relations.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. # Copyright 2019 New Vector Ltd
  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 Any, Dict, List, Optional, Tuple
  16. import attr
  17. from synapse.api.errors import SynapseError
  18. from synapse.types import JsonDict
  19. logger = logging.getLogger(__name__)
  20. @attr.s(slots=True)
  21. class PaginationChunk:
  22. """Returned by relation pagination APIs.
  23. Attributes:
  24. chunk: The rows returned by pagination
  25. next_batch: Token to fetch next set of results with, if
  26. None then there are no more results.
  27. prev_batch: Token to fetch previous set of results with, if
  28. None then there are no previous results.
  29. """
  30. chunk = attr.ib(type=List[JsonDict])
  31. next_batch = attr.ib(type=Optional[Any], default=None)
  32. prev_batch = attr.ib(type=Optional[Any], default=None)
  33. def to_dict(self) -> Dict[str, Any]:
  34. d = {"chunk": self.chunk}
  35. if self.next_batch:
  36. d["next_batch"] = self.next_batch.to_string()
  37. if self.prev_batch:
  38. d["prev_batch"] = self.prev_batch.to_string()
  39. return d
  40. @attr.s(frozen=True, slots=True)
  41. class RelationPaginationToken:
  42. """Pagination token for relation pagination API.
  43. As the results are in topological order, we can use the
  44. `topological_ordering` and `stream_ordering` fields of the events at the
  45. boundaries of the chunk as pagination tokens.
  46. Attributes:
  47. topological: The topological ordering of the boundary event
  48. stream: The stream ordering of the boundary event.
  49. """
  50. topological = attr.ib(type=int)
  51. stream = attr.ib(type=int)
  52. @staticmethod
  53. def from_string(string: str) -> "RelationPaginationToken":
  54. try:
  55. t, s = string.split("-")
  56. return RelationPaginationToken(int(t), int(s))
  57. except ValueError:
  58. raise SynapseError(400, "Invalid relation pagination token")
  59. def to_string(self) -> str:
  60. return "%d-%d" % (self.topological, self.stream)
  61. def as_tuple(self) -> Tuple[Any, ...]:
  62. return attr.astuple(self)
  63. @attr.s(frozen=True, slots=True)
  64. class AggregationPaginationToken:
  65. """Pagination token for relation aggregation pagination API.
  66. As the results are order by count and then MAX(stream_ordering) of the
  67. aggregation groups, we can just use them as our pagination token.
  68. Attributes:
  69. count: The count of relations in the boundary group.
  70. stream: The MAX stream ordering in the boundary group.
  71. """
  72. count = attr.ib(type=int)
  73. stream = attr.ib(type=int)
  74. @staticmethod
  75. def from_string(string: str) -> "AggregationPaginationToken":
  76. try:
  77. c, s = string.split("-")
  78. return AggregationPaginationToken(int(c), int(s))
  79. except ValueError:
  80. raise SynapseError(400, "Invalid aggregation pagination token")
  81. def to_string(self) -> str:
  82. return "%d-%d" % (self.count, self.stream)
  83. def as_tuple(self) -> Tuple[Any, ...]:
  84. return attr.astuple(self)