types.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014, 2015 OpenMarket 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. from synapse.api.errors import SynapseError
  16. from collections import namedtuple
  17. class DomainSpecificString(
  18. namedtuple("DomainSpecificString", ("localpart", "domain"))
  19. ):
  20. """Common base class among ID/name strings that have a local part and a
  21. domain name, prefixed with a sigil.
  22. Has the fields:
  23. 'localpart' : The local part of the name (without the leading sigil)
  24. 'domain' : The domain part of the name
  25. """
  26. # Deny iteration because it will bite you if you try to create a singleton
  27. # set by:
  28. # users = set(user)
  29. def __iter__(self):
  30. raise ValueError("Attempted to iterate a %s" % (type(self).__name__,))
  31. # Because this class is a namedtuple of strings and booleans, it is deeply
  32. # immutable.
  33. def __copy__(self):
  34. return self
  35. def __deepcopy__(self, memo):
  36. return self
  37. @classmethod
  38. def from_string(cls, s):
  39. """Parse the string given by 's' into a structure object."""
  40. if s[0] != cls.SIGIL:
  41. raise SynapseError(400, "Expected %s string to start with '%s'" % (
  42. cls.__name__, cls.SIGIL,
  43. ))
  44. parts = s[1:].split(':', 1)
  45. if len(parts) != 2:
  46. raise SynapseError(
  47. 400, "Expected %s of the form '%slocalname:domain'" % (
  48. cls.__name__, cls.SIGIL,
  49. )
  50. )
  51. domain = parts[1]
  52. # This code will need changing if we want to support multiple domain
  53. # names on one HS
  54. return cls(localpart=parts[0], domain=domain)
  55. def to_string(self):
  56. """Return a string encoding the fields of the structure object."""
  57. return "%s%s:%s" % (self.SIGIL, self.localpart, self.domain)
  58. __str__ = to_string
  59. @classmethod
  60. def create(cls, localpart, domain,):
  61. return cls(localpart=localpart, domain=domain)
  62. class UserID(DomainSpecificString):
  63. """Structure representing a user ID."""
  64. SIGIL = "@"
  65. class RoomAlias(DomainSpecificString):
  66. """Structure representing a room name."""
  67. SIGIL = "#"
  68. class RoomID(DomainSpecificString):
  69. """Structure representing a room id. """
  70. SIGIL = "!"
  71. class EventID(DomainSpecificString):
  72. """Structure representing an event id. """
  73. SIGIL = "$"
  74. class StreamToken(
  75. namedtuple(
  76. "Token",
  77. ("room_key", "presence_key", "typing_key", "receipt_key")
  78. )
  79. ):
  80. _SEPARATOR = "_"
  81. @classmethod
  82. def from_string(cls, string):
  83. try:
  84. keys = string.split(cls._SEPARATOR)
  85. if len(keys) == len(cls._fields) - 1:
  86. # i.e. old token from before receipt_key
  87. keys.append("0")
  88. return cls(*keys)
  89. except:
  90. raise SynapseError(400, "Invalid Token")
  91. def to_string(self):
  92. return self._SEPARATOR.join([str(k) for k in self])
  93. @property
  94. def room_stream_id(self):
  95. # TODO(markjh): Awful hack to work around hacks in the presence tests
  96. # which assume that the keys are integers.
  97. if type(self.room_key) is int:
  98. return self.room_key
  99. else:
  100. return int(self.room_key[1:].split("-")[-1])
  101. def is_after(self, other_token):
  102. """Does this token contain events that the other doesn't?"""
  103. return (
  104. (other_token.room_stream_id < self.room_stream_id)
  105. or (int(other_token.presence_key) < int(self.presence_key))
  106. or (int(other_token.typing_key) < int(self.typing_key))
  107. or (int(other_token.receipt_key) < int(self.receipt_key))
  108. )
  109. def copy_and_advance(self, key, new_value):
  110. """Advance the given key in the token to a new value if and only if the
  111. new value is after the old value.
  112. """
  113. new_token = self.copy_and_replace(key, new_value)
  114. if key == "room_key":
  115. new_id = new_token.room_stream_id
  116. old_id = self.room_stream_id
  117. else:
  118. new_id = int(getattr(new_token, key))
  119. old_id = int(getattr(self, key))
  120. if old_id < new_id:
  121. return new_token
  122. else:
  123. return self
  124. def copy_and_replace(self, key, new_value):
  125. d = self._asdict()
  126. d[key] = new_value
  127. return StreamToken(**d)
  128. class RoomStreamToken(namedtuple("_StreamToken", "topological stream")):
  129. """Tokens are positions between events. The token "s1" comes after event 1.
  130. s0 s1
  131. | |
  132. [0] V [1] V [2]
  133. Tokens can either be a point in the live event stream or a cursor going
  134. through historic events.
  135. When traversing the live event stream events are ordered by when they
  136. arrived at the homeserver.
  137. When traversing historic events the events are ordered by their depth in
  138. the event graph "topological_ordering" and then by when they arrived at the
  139. homeserver "stream_ordering".
  140. Live tokens start with an "s" followed by the "stream_ordering" id of the
  141. event it comes after. Historic tokens start with a "t" followed by the
  142. "topological_ordering" id of the event it comes after, followed by "-",
  143. followed by the "stream_ordering" id of the event it comes after.
  144. """
  145. __slots__ = []
  146. @classmethod
  147. def parse(cls, string):
  148. try:
  149. if string[0] == 's':
  150. return cls(topological=None, stream=int(string[1:]))
  151. if string[0] == 't':
  152. parts = string[1:].split('-', 1)
  153. return cls(topological=int(parts[0]), stream=int(parts[1]))
  154. except:
  155. pass
  156. raise SynapseError(400, "Invalid token %r" % (string,))
  157. @classmethod
  158. def parse_stream_token(cls, string):
  159. try:
  160. if string[0] == 's':
  161. return cls(topological=None, stream=int(string[1:]))
  162. except:
  163. pass
  164. raise SynapseError(400, "Invalid token %r" % (string,))
  165. def __str__(self):
  166. if self.topological is not None:
  167. return "t%d-%d" % (self.topological, self.stream)
  168. else:
  169. return "s%d" % (self.stream,)