Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

1219 рядки
40 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2019 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 abc
  16. import re
  17. import string
  18. from enum import Enum
  19. from typing import (
  20. TYPE_CHECKING,
  21. AbstractSet,
  22. Any,
  23. ClassVar,
  24. Dict,
  25. List,
  26. Literal,
  27. Mapping,
  28. Match,
  29. MutableMapping,
  30. NoReturn,
  31. Optional,
  32. Set,
  33. Tuple,
  34. Type,
  35. TypeVar,
  36. Union,
  37. overload,
  38. )
  39. import attr
  40. from immutabledict import immutabledict
  41. from signedjson.key import decode_verify_key_bytes
  42. from signedjson.types import VerifyKey
  43. from typing_extensions import TypedDict
  44. from unpaddedbase64 import decode_base64
  45. from zope.interface import Interface
  46. from twisted.internet.defer import CancelledError
  47. from twisted.internet.interfaces import (
  48. IReactorCore,
  49. IReactorPluggableNameResolver,
  50. IReactorSSL,
  51. IReactorTCP,
  52. IReactorThreads,
  53. IReactorTime,
  54. IReactorUNIX,
  55. )
  56. from synapse.api.errors import Codes, SynapseError
  57. from synapse.util.cancellation import cancellable
  58. from synapse.util.stringutils import parse_and_validate_server_name
  59. if TYPE_CHECKING:
  60. from typing_extensions import Self
  61. from synapse.appservice.api import ApplicationService
  62. from synapse.storage.databases.main import DataStore, PurgeEventsStore
  63. from synapse.storage.databases.main.appservice import ApplicationServiceWorkerStore
  64. # Define a state map type from type/state_key to T (usually an event ID or
  65. # event)
  66. T = TypeVar("T")
  67. StateKey = Tuple[str, str]
  68. StateMap = Mapping[StateKey, T]
  69. MutableStateMap = MutableMapping[StateKey, T]
  70. # JSON types. These could be made stronger, but will do for now.
  71. # A "simple" (canonical) JSON value.
  72. SimpleJsonValue = Optional[Union[str, int, bool]]
  73. JsonValue = Union[List[SimpleJsonValue], Tuple[SimpleJsonValue, ...], SimpleJsonValue]
  74. # A JSON-serialisable dict.
  75. JsonDict = Dict[str, Any]
  76. # A JSON-serialisable mapping; roughly speaking an immutable JSONDict.
  77. # Useful when you have a TypedDict which isn't going to be mutated and you don't want
  78. # to cast to JsonDict everywhere.
  79. JsonMapping = Mapping[str, Any]
  80. # A JSON-serialisable object.
  81. JsonSerializable = object
  82. # Collection[str] that does not include str itself; str being a Sequence[str]
  83. # is very misleading and results in bugs.
  84. #
  85. # StrCollection is an unordered collection of strings. If ordering is important,
  86. # StrSequence can be used instead.
  87. StrCollection = Union[Tuple[str, ...], List[str], AbstractSet[str]]
  88. # Sequence[str] that does not include str itself; str being a Sequence[str]
  89. # is very misleading and results in bugs.
  90. #
  91. # Unlike StrCollection, StrSequence is an ordered collection of strings.
  92. StrSequence = Union[Tuple[str, ...], List[str]]
  93. # Note that this seems to require inheriting *directly* from Interface in order
  94. # for mypy-zope to realize it is an interface.
  95. class ISynapseReactor(
  96. IReactorTCP,
  97. IReactorSSL,
  98. IReactorUNIX,
  99. IReactorPluggableNameResolver,
  100. IReactorTime,
  101. IReactorCore,
  102. IReactorThreads,
  103. Interface,
  104. ):
  105. """The interfaces necessary for Synapse to function."""
  106. @attr.s(frozen=True, slots=True, auto_attribs=True)
  107. class Requester:
  108. """
  109. Represents the user making a request
  110. Attributes:
  111. user: id of the user making the request
  112. access_token_id: *ID* of the access token used for this request, or
  113. None for appservices, guests, and tokens generated by the admin API
  114. is_guest: True if the user making this request is a guest user
  115. shadow_banned: True if the user making this request has been shadow-banned.
  116. device_id: device_id which was set at authentication time, or
  117. None for appservices, guests, and tokens generated by the admin API
  118. app_service: the AS requesting on behalf of the user
  119. authenticated_entity: The entity that authenticated when making the request.
  120. This is different to the user_id when an admin user or the server is
  121. "puppeting" the user.
  122. """
  123. user: "UserID"
  124. access_token_id: Optional[int]
  125. is_guest: bool
  126. scope: Set[str]
  127. shadow_banned: bool
  128. device_id: Optional[str]
  129. app_service: Optional["ApplicationService"]
  130. authenticated_entity: str
  131. def serialize(self) -> Dict[str, Any]:
  132. """Converts self to a type that can be serialized as JSON, and then
  133. deserialized by `deserialize`
  134. Returns:
  135. dict
  136. """
  137. return {
  138. "user_id": self.user.to_string(),
  139. "access_token_id": self.access_token_id,
  140. "is_guest": self.is_guest,
  141. "scope": list(self.scope),
  142. "shadow_banned": self.shadow_banned,
  143. "device_id": self.device_id,
  144. "app_server_id": self.app_service.id if self.app_service else None,
  145. "authenticated_entity": self.authenticated_entity,
  146. }
  147. @staticmethod
  148. def deserialize(
  149. store: "ApplicationServiceWorkerStore", input: Dict[str, Any]
  150. ) -> "Requester":
  151. """Converts a dict that was produced by `serialize` back into a
  152. Requester.
  153. Args:
  154. store: Used to convert AS ID to AS object
  155. input: A dict produced by `serialize`
  156. Returns:
  157. Requester
  158. """
  159. appservice = None
  160. if input["app_server_id"]:
  161. appservice = store.get_app_service_by_id(input["app_server_id"])
  162. return Requester(
  163. user=UserID.from_string(input["user_id"]),
  164. access_token_id=input["access_token_id"],
  165. is_guest=input["is_guest"],
  166. scope=set(input.get("scope", [])),
  167. shadow_banned=input["shadow_banned"],
  168. device_id=input["device_id"],
  169. app_service=appservice,
  170. authenticated_entity=input["authenticated_entity"],
  171. )
  172. def create_requester(
  173. user_id: Union[str, "UserID"],
  174. access_token_id: Optional[int] = None,
  175. is_guest: bool = False,
  176. scope: StrCollection = (),
  177. shadow_banned: bool = False,
  178. device_id: Optional[str] = None,
  179. app_service: Optional["ApplicationService"] = None,
  180. authenticated_entity: Optional[str] = None,
  181. ) -> Requester:
  182. """
  183. Create a new ``Requester`` object
  184. Args:
  185. user_id: id of the user making the request
  186. access_token_id: *ID* of the access token used for this
  187. request, or None if it came via the appservice API or similar
  188. is_guest: True if the user making this request is a guest user
  189. scope: the scope of the access token used for this request, if any
  190. shadow_banned: True if the user making this request is shadow-banned.
  191. device_id: device_id which was set at authentication time
  192. app_service: the AS requesting on behalf of the user
  193. authenticated_entity: The entity that authenticated when making the request.
  194. This is different to the user_id when an admin user or the server is
  195. "puppeting" the user.
  196. Returns:
  197. Requester
  198. """
  199. if not isinstance(user_id, UserID):
  200. user_id = UserID.from_string(user_id)
  201. if authenticated_entity is None:
  202. authenticated_entity = user_id.to_string()
  203. scope = set(scope)
  204. return Requester(
  205. user_id,
  206. access_token_id,
  207. is_guest,
  208. scope,
  209. shadow_banned,
  210. device_id,
  211. app_service,
  212. authenticated_entity,
  213. )
  214. def get_domain_from_id(string: str) -> str:
  215. idx = string.find(":")
  216. if idx == -1:
  217. raise SynapseError(400, "Invalid ID: %r" % (string,))
  218. return string[idx + 1 :]
  219. def get_localpart_from_id(string: str) -> str:
  220. idx = string.find(":")
  221. if idx == -1:
  222. raise SynapseError(400, "Invalid ID: %r" % (string,))
  223. return string[1:idx]
  224. DS = TypeVar("DS", bound="DomainSpecificString")
  225. @attr.s(slots=True, frozen=True, repr=False, auto_attribs=True)
  226. class DomainSpecificString(metaclass=abc.ABCMeta):
  227. """Common base class among ID/name strings that have a local part and a
  228. domain name, prefixed with a sigil.
  229. Has the fields:
  230. 'localpart' : The local part of the name (without the leading sigil)
  231. 'domain' : The domain part of the name
  232. """
  233. SIGIL: ClassVar[str] = abc.abstractproperty() # type: ignore
  234. localpart: str
  235. domain: str
  236. # Because this is a frozen class, it is deeply immutable.
  237. def __copy__(self: DS) -> DS:
  238. return self
  239. def __deepcopy__(self: DS, memo: Dict[str, object]) -> DS:
  240. return self
  241. @classmethod
  242. def from_string(cls: Type[DS], s: str) -> DS:
  243. """Parse the string given by 's' into a structure object."""
  244. if len(s) < 1 or s[0:1] != cls.SIGIL:
  245. raise SynapseError(
  246. 400,
  247. "Expected %s string to start with '%s'" % (cls.__name__, cls.SIGIL),
  248. Codes.INVALID_PARAM,
  249. )
  250. parts = s[1:].split(":", 1)
  251. if len(parts) != 2:
  252. raise SynapseError(
  253. 400,
  254. "Expected %s of the form '%slocalname:domain'"
  255. % (cls.__name__, cls.SIGIL),
  256. Codes.INVALID_PARAM,
  257. )
  258. domain = parts[1]
  259. # This code will need changing if we want to support multiple domain
  260. # names on one HS
  261. return cls(localpart=parts[0], domain=domain)
  262. def to_string(self) -> str:
  263. """Return a string encoding the fields of the structure object."""
  264. return "%s%s:%s" % (self.SIGIL, self.localpart, self.domain)
  265. @classmethod
  266. def is_valid(cls: Type[DS], s: str) -> bool:
  267. """Parses the input string and attempts to ensure it is valid."""
  268. # TODO: this does not reject an empty localpart or an overly-long string.
  269. # See https://spec.matrix.org/v1.2/appendices/#identifier-grammar
  270. try:
  271. obj = cls.from_string(s)
  272. # Apply additional validation to the domain. This is only done
  273. # during is_valid (and not part of from_string) since it is
  274. # possible for invalid data to exist in room-state, etc.
  275. parse_and_validate_server_name(obj.domain)
  276. return True
  277. except Exception:
  278. return False
  279. __repr__ = to_string
  280. @attr.s(slots=True, frozen=True, repr=False)
  281. class UserID(DomainSpecificString):
  282. """Structure representing a user ID."""
  283. SIGIL = "@"
  284. @attr.s(slots=True, frozen=True, repr=False)
  285. class RoomAlias(DomainSpecificString):
  286. """Structure representing a room name."""
  287. SIGIL = "#"
  288. @attr.s(slots=True, frozen=True, repr=False)
  289. class RoomID(DomainSpecificString):
  290. """Structure representing a room id."""
  291. SIGIL = "!"
  292. @attr.s(slots=True, frozen=True, repr=False)
  293. class EventID(DomainSpecificString):
  294. """Structure representing an event id."""
  295. SIGIL = "$"
  296. MXID_LOCALPART_ALLOWED_CHARACTERS = set(
  297. "_-./=+" + string.ascii_lowercase + string.digits
  298. )
  299. # Guest user IDs are purely numeric.
  300. GUEST_USER_ID_PATTERN = re.compile(r"^\d+$")
  301. def contains_invalid_mxid_characters(localpart: str) -> bool:
  302. """Check for characters not allowed in an mxid or groupid localpart
  303. Args:
  304. localpart: the localpart to be checked
  305. use_extended_character_set: True to use the extended allowed characters
  306. from MSC4009.
  307. Returns:
  308. True if there are any naughty characters
  309. """
  310. return any(c not in MXID_LOCALPART_ALLOWED_CHARACTERS for c in localpart)
  311. UPPER_CASE_PATTERN = re.compile(b"[A-Z_]")
  312. # the following is a pattern which matches '=', and bytes which are not allowed in a mxid
  313. # localpart.
  314. #
  315. # It works by:
  316. # * building a string containing the allowed characters (excluding '=')
  317. # * escaping every special character with a backslash (to stop '-' being interpreted as a
  318. # range operator)
  319. # * wrapping it in a '[^...]' regex
  320. # * converting the whole lot to a 'bytes' sequence, so that we can use it to match
  321. # bytes rather than strings
  322. #
  323. NON_MXID_CHARACTER_PATTERN = re.compile(
  324. ("[^%s]" % (re.escape("".join(MXID_LOCALPART_ALLOWED_CHARACTERS - {"="})),)).encode(
  325. "ascii"
  326. )
  327. )
  328. def map_username_to_mxid_localpart(
  329. username: Union[str, bytes], case_sensitive: bool = False
  330. ) -> str:
  331. """Map a username onto a string suitable for a MXID
  332. This follows the algorithm laid out at
  333. https://matrix.org/docs/spec/appendices.html#mapping-from-other-character-sets.
  334. Args:
  335. username: username to be mapped
  336. case_sensitive: true if TEST and test should be mapped
  337. onto different mxids
  338. Returns:
  339. string suitable for a mxid localpart
  340. """
  341. if not isinstance(username, bytes):
  342. username = username.encode("utf-8")
  343. # first we sort out upper-case characters
  344. if case_sensitive:
  345. def f1(m: Match[bytes]) -> bytes:
  346. return b"_" + m.group().lower()
  347. username = UPPER_CASE_PATTERN.sub(f1, username)
  348. else:
  349. username = username.lower()
  350. # then we sort out non-ascii characters by converting to the hex equivalent.
  351. def f2(m: Match[bytes]) -> bytes:
  352. return b"=%02x" % (m.group()[0],)
  353. username = NON_MXID_CHARACTER_PATTERN.sub(f2, username)
  354. # we also do the =-escaping to mxids starting with an underscore.
  355. username = re.sub(b"^_", b"=5f", username)
  356. # we should now only have ascii bytes left, so can decode back to a string.
  357. return username.decode("ascii")
  358. @attr.s(frozen=True, slots=True, order=False)
  359. class AbstractMultiWriterStreamToken(metaclass=abc.ABCMeta):
  360. """An abstract stream token class for streams that supports multiple
  361. writers.
  362. This works by keeping track of the stream position of each writer,
  363. represented by a default `stream` attribute and a map of instance name to
  364. stream position of any writers that are ahead of the default stream
  365. position.
  366. """
  367. stream: int = attr.ib(validator=attr.validators.instance_of(int), kw_only=True)
  368. instance_map: "immutabledict[str, int]" = attr.ib(
  369. factory=immutabledict,
  370. validator=attr.validators.deep_mapping(
  371. key_validator=attr.validators.instance_of(str),
  372. value_validator=attr.validators.instance_of(int),
  373. mapping_validator=attr.validators.instance_of(immutabledict),
  374. ),
  375. kw_only=True,
  376. )
  377. @classmethod
  378. @abc.abstractmethod
  379. async def parse(cls, store: "DataStore", string: str) -> "Self":
  380. """Parse the string representation of the token."""
  381. ...
  382. @abc.abstractmethod
  383. async def to_string(self, store: "DataStore") -> str:
  384. """Serialize the token into its string representation."""
  385. ...
  386. def copy_and_advance(self, other: "Self") -> "Self":
  387. """Return a new token such that if an event is after both this token and
  388. the other token, then its after the returned token too.
  389. """
  390. max_stream = max(self.stream, other.stream)
  391. instance_map = {
  392. instance: max(
  393. self.instance_map.get(instance, self.stream),
  394. other.instance_map.get(instance, other.stream),
  395. )
  396. for instance in set(self.instance_map).union(other.instance_map)
  397. }
  398. return attr.evolve(
  399. self, stream=max_stream, instance_map=immutabledict(instance_map)
  400. )
  401. def get_max_stream_pos(self) -> int:
  402. """Get the maximum stream position referenced in this token.
  403. The corresponding "min" position is, by definition just `self.stream`.
  404. This is used to handle tokens that have non-empty `instance_map`, and so
  405. reference stream positions after the `self.stream` position.
  406. """
  407. return max(self.instance_map.values(), default=self.stream)
  408. def get_stream_pos_for_instance(self, instance_name: str) -> int:
  409. """Get the stream position that the given writer was at at this token."""
  410. # If we don't have an entry for the instance we can assume that it was
  411. # at `self.stream`.
  412. return self.instance_map.get(instance_name, self.stream)
  413. @attr.s(frozen=True, slots=True, order=False)
  414. class RoomStreamToken(AbstractMultiWriterStreamToken):
  415. """Tokens are positions between events. The token "s1" comes after event 1.
  416. s0 s1
  417. | |
  418. [0] ▼ [1] ▼ [2]
  419. Tokens can either be a point in the live event stream or a cursor going
  420. through historic events.
  421. When traversing the live event stream, events are ordered by
  422. `stream_ordering` (when they arrived at the homeserver).
  423. When traversing historic events, events are first ordered by their `depth`
  424. (`topological_ordering` in the event graph) and tie-broken by
  425. `stream_ordering` (when the event arrived at the homeserver).
  426. If you're looking for more info about what a token with all of the
  427. underscores means, ex.
  428. `s2633508_17_338_6732159_1082514_541479_274711_265584_1`, see the docstring
  429. for `StreamToken` below.
  430. ---
  431. Live tokens start with an "s" followed by the `stream_ordering` of the event
  432. that comes before the position of the token. Said another way:
  433. `stream_ordering` uniquely identifies a persisted event. The live token
  434. means "the position just after the event identified by `stream_ordering`".
  435. An example token is:
  436. s2633508
  437. ---
  438. Historic tokens start with a "t" followed by the `depth`
  439. (`topological_ordering` in the event graph) of the event that comes before
  440. the position of the token, followed by "-", followed by the
  441. `stream_ordering` of the event that comes before the position of the token.
  442. An example token is:
  443. t426-2633508
  444. ---
  445. There is also a third mode for live tokens where the token starts with "m",
  446. which is sometimes used when using sharded event persisters. In this case
  447. the events stream is considered to be a set of streams (one for each writer)
  448. and the token encodes the vector clock of positions of each writer in their
  449. respective streams.
  450. The format of the token in such case is an initial integer min position,
  451. followed by the mapping of instance ID to position separated by '.' and '~':
  452. m{min_pos}~{writer1}.{pos1}~{writer2}.{pos2}. ...
  453. The `min_pos` corresponds to the minimum position all writers have persisted
  454. up to, and then only writers that are ahead of that position need to be
  455. encoded. An example token is:
  456. m56~2.58~3.59
  457. Which corresponds to a set of three (or more writers) where instances 2 and
  458. 3 (these are instance IDs that can be looked up in the DB to fetch the more
  459. commonly used instance names) are at positions 58 and 59 respectively, and
  460. all other instances are at position 56.
  461. Note: The `RoomStreamToken` cannot have both a topological part and an
  462. instance map.
  463. ---
  464. For caching purposes, `RoomStreamToken`s and by extension, all their
  465. attributes, must be hashable.
  466. """
  467. topological: Optional[int] = attr.ib(
  468. validator=attr.validators.optional(attr.validators.instance_of(int)),
  469. kw_only=True,
  470. default=None,
  471. )
  472. def __attrs_post_init__(self) -> None:
  473. """Validates that both `topological` and `instance_map` aren't set."""
  474. if self.instance_map and self.topological:
  475. raise ValueError(
  476. "Cannot set both 'topological' and 'instance_map' on 'RoomStreamToken'."
  477. )
  478. @classmethod
  479. async def parse(cls, store: "PurgeEventsStore", string: str) -> "RoomStreamToken":
  480. try:
  481. if string[0] == "s":
  482. return cls(topological=None, stream=int(string[1:]))
  483. if string[0] == "t":
  484. parts = string[1:].split("-", 1)
  485. return cls(topological=int(parts[0]), stream=int(parts[1]))
  486. if string[0] == "m":
  487. parts = string[1:].split("~")
  488. stream = int(parts[0])
  489. instance_map = {}
  490. for part in parts[1:]:
  491. key, value = part.split(".")
  492. instance_id = int(key)
  493. pos = int(value)
  494. instance_name = await store.get_name_from_instance_id(instance_id) # type: ignore[attr-defined]
  495. instance_map[instance_name] = pos
  496. return cls(
  497. topological=None,
  498. stream=stream,
  499. instance_map=immutabledict(instance_map),
  500. )
  501. except CancelledError:
  502. raise
  503. except Exception:
  504. pass
  505. raise SynapseError(400, "Invalid room stream token %r" % (string,))
  506. @classmethod
  507. def parse_stream_token(cls, string: str) -> "RoomStreamToken":
  508. try:
  509. if string[0] == "s":
  510. return cls(topological=None, stream=int(string[1:]))
  511. except Exception:
  512. pass
  513. raise SynapseError(400, "Invalid room stream token %r" % (string,))
  514. def copy_and_advance(self, other: "RoomStreamToken") -> "RoomStreamToken":
  515. """Return a new token such that if an event is after both this token and
  516. the other token, then its after the returned token too.
  517. """
  518. if self.topological or other.topological:
  519. raise Exception("Can't advance topological tokens")
  520. return super().copy_and_advance(other)
  521. def as_historical_tuple(self) -> Tuple[int, int]:
  522. """Returns a tuple of `(topological, stream)` for historical tokens.
  523. Raises if not an historical token (i.e. doesn't have a topological part).
  524. """
  525. if self.topological is None:
  526. raise Exception(
  527. "Cannot call `RoomStreamToken.as_historical_tuple` on live token"
  528. )
  529. return self.topological, self.stream
  530. def get_stream_pos_for_instance(self, instance_name: str) -> int:
  531. """Get the stream position that the given writer was at at this token.
  532. This only makes sense for "live" tokens that may have a vector clock
  533. component, and so asserts that this is a "live" token.
  534. """
  535. assert self.topological is None
  536. # If we don't have an entry for the instance we can assume that it was
  537. # at `self.stream`.
  538. return self.instance_map.get(instance_name, self.stream)
  539. async def to_string(self, store: "DataStore") -> str:
  540. if self.topological is not None:
  541. return "t%d-%d" % (self.topological, self.stream)
  542. elif self.instance_map:
  543. entries = []
  544. for name, pos in self.instance_map.items():
  545. if pos <= self.stream:
  546. # Ignore instances who are below the minimum stream position
  547. # (we might know they've advanced without seeing a recent
  548. # write from them).
  549. continue
  550. instance_id = await store.get_id_for_instance(name)
  551. entries.append(f"{instance_id}.{pos}")
  552. encoded_map = "~".join(entries)
  553. return f"m{self.stream}~{encoded_map}"
  554. else:
  555. return "s%d" % (self.stream,)
  556. @attr.s(frozen=True, slots=True, order=False)
  557. class MultiWriterStreamToken(AbstractMultiWriterStreamToken):
  558. """A basic stream token class for streams that supports multiple writers."""
  559. @classmethod
  560. async def parse(cls, store: "DataStore", string: str) -> "MultiWriterStreamToken":
  561. try:
  562. if string[0].isdigit():
  563. return cls(stream=int(string))
  564. if string[0] == "m":
  565. parts = string[1:].split("~")
  566. stream = int(parts[0])
  567. instance_map = {}
  568. for part in parts[1:]:
  569. key, value = part.split(".")
  570. instance_id = int(key)
  571. pos = int(value)
  572. instance_name = await store.get_name_from_instance_id(instance_id)
  573. instance_map[instance_name] = pos
  574. return cls(
  575. stream=stream,
  576. instance_map=immutabledict(instance_map),
  577. )
  578. except CancelledError:
  579. raise
  580. except Exception:
  581. pass
  582. raise SynapseError(400, "Invalid stream token %r" % (string,))
  583. async def to_string(self, store: "DataStore") -> str:
  584. if self.instance_map:
  585. entries = []
  586. for name, pos in self.instance_map.items():
  587. if pos <= self.stream:
  588. # Ignore instances who are below the minimum stream position
  589. # (we might know they've advanced without seeing a recent
  590. # write from them).
  591. continue
  592. instance_id = await store.get_id_for_instance(name)
  593. entries.append(f"{instance_id}.{pos}")
  594. encoded_map = "~".join(entries)
  595. return f"m{self.stream}~{encoded_map}"
  596. else:
  597. return str(self.stream)
  598. @staticmethod
  599. def is_stream_position_in_range(
  600. low: Optional["AbstractMultiWriterStreamToken"],
  601. high: Optional["AbstractMultiWriterStreamToken"],
  602. instance_name: Optional[str],
  603. pos: int,
  604. ) -> bool:
  605. """Checks if a given persisted position is between the two given tokens.
  606. If `instance_name` is None then the row was persisted before multi
  607. writer support.
  608. """
  609. if low:
  610. if instance_name:
  611. low_stream = low.instance_map.get(instance_name, low.stream)
  612. else:
  613. low_stream = low.stream
  614. if pos <= low_stream:
  615. return False
  616. if high:
  617. if instance_name:
  618. high_stream = high.instance_map.get(instance_name, high.stream)
  619. else:
  620. high_stream = high.stream
  621. if high_stream < pos:
  622. return False
  623. return True
  624. class StreamKeyType(Enum):
  625. """Known stream types.
  626. A stream is a list of entities ordered by an incrementing "stream token".
  627. """
  628. ROOM = "room_key"
  629. PRESENCE = "presence_key"
  630. TYPING = "typing_key"
  631. RECEIPT = "receipt_key"
  632. ACCOUNT_DATA = "account_data_key"
  633. PUSH_RULES = "push_rules_key"
  634. TO_DEVICE = "to_device_key"
  635. DEVICE_LIST = "device_list_key"
  636. UN_PARTIAL_STATED_ROOMS = "un_partial_stated_rooms_key"
  637. @attr.s(slots=True, frozen=True, auto_attribs=True)
  638. class StreamToken:
  639. """A collection of keys joined together by underscores in the following
  640. order and which represent the position in their respective streams.
  641. ex. `s2633508_17_338_6732159_1082514_541479_274711_265584_1_379`
  642. 1. `room_key`: `s2633508` which is a `RoomStreamToken`
  643. - `RoomStreamToken`'s can also look like `t426-2633508` or `m56~2.58~3.59`
  644. - See the docstring for `RoomStreamToken` for more details.
  645. 2. `presence_key`: `17`
  646. 3. `typing_key`: `338`
  647. 4. `receipt_key`: `6732159`
  648. 5. `account_data_key`: `1082514`
  649. 6. `push_rules_key`: `541479`
  650. 7. `to_device_key`: `274711`
  651. 8. `device_list_key`: `265584`
  652. 9. `groups_key`: `1` (note that this key is now unused)
  653. 10. `un_partial_stated_rooms_key`: `379`
  654. You can see how many of these keys correspond to the various
  655. fields in a "/sync" response:
  656. ```json
  657. {
  658. "next_batch": "s12_4_0_1_1_1_1_4_1_1",
  659. "presence": {
  660. "events": []
  661. },
  662. "device_lists": {
  663. "changed": []
  664. },
  665. "rooms": {
  666. "join": {
  667. "!QrZlfIDQLNLdZHqTnt:hs1": {
  668. "timeline": {
  669. "events": [],
  670. "prev_batch": "s10_4_0_1_1_1_1_4_1_1",
  671. "limited": false
  672. },
  673. "state": {
  674. "events": []
  675. },
  676. "account_data": {
  677. "events": []
  678. },
  679. "ephemeral": {
  680. "events": []
  681. }
  682. }
  683. }
  684. }
  685. }
  686. ```
  687. ---
  688. For caching purposes, `StreamToken`s and by extension, all their attributes,
  689. must be hashable.
  690. """
  691. room_key: RoomStreamToken = attr.ib(
  692. validator=attr.validators.instance_of(RoomStreamToken)
  693. )
  694. presence_key: int
  695. typing_key: int
  696. receipt_key: MultiWriterStreamToken = attr.ib(
  697. validator=attr.validators.instance_of(MultiWriterStreamToken)
  698. )
  699. account_data_key: int
  700. push_rules_key: int
  701. to_device_key: int
  702. device_list_key: int
  703. # Note that the groups key is no longer used and may have bogus values.
  704. groups_key: int
  705. un_partial_stated_rooms_key: int
  706. _SEPARATOR = "_"
  707. START: ClassVar["StreamToken"]
  708. @classmethod
  709. @cancellable
  710. async def from_string(cls, store: "DataStore", string: str) -> "StreamToken":
  711. """
  712. Creates a RoomStreamToken from its textual representation.
  713. """
  714. try:
  715. keys = string.split(cls._SEPARATOR)
  716. while len(keys) < len(attr.fields(cls)):
  717. # i.e. old token from before receipt_key
  718. keys.append("0")
  719. (
  720. room_key,
  721. presence_key,
  722. typing_key,
  723. receipt_key,
  724. account_data_key,
  725. push_rules_key,
  726. to_device_key,
  727. device_list_key,
  728. groups_key,
  729. un_partial_stated_rooms_key,
  730. ) = keys
  731. return cls(
  732. room_key=await RoomStreamToken.parse(store, room_key),
  733. presence_key=int(presence_key),
  734. typing_key=int(typing_key),
  735. receipt_key=await MultiWriterStreamToken.parse(store, receipt_key),
  736. account_data_key=int(account_data_key),
  737. push_rules_key=int(push_rules_key),
  738. to_device_key=int(to_device_key),
  739. device_list_key=int(device_list_key),
  740. groups_key=int(groups_key),
  741. un_partial_stated_rooms_key=int(un_partial_stated_rooms_key),
  742. )
  743. except CancelledError:
  744. raise
  745. except Exception:
  746. raise SynapseError(400, "Invalid stream token")
  747. async def to_string(self, store: "DataStore") -> str:
  748. return self._SEPARATOR.join(
  749. [
  750. await self.room_key.to_string(store),
  751. str(self.presence_key),
  752. str(self.typing_key),
  753. await self.receipt_key.to_string(store),
  754. str(self.account_data_key),
  755. str(self.push_rules_key),
  756. str(self.to_device_key),
  757. str(self.device_list_key),
  758. # Note that the groups key is no longer used, but it is still
  759. # serialized so that there will not be confusion in the future
  760. # if additional tokens are added.
  761. str(self.groups_key),
  762. str(self.un_partial_stated_rooms_key),
  763. ]
  764. )
  765. @property
  766. def room_stream_id(self) -> int:
  767. return self.room_key.stream
  768. def copy_and_advance(self, key: StreamKeyType, new_value: Any) -> "StreamToken":
  769. """Advance the given key in the token to a new value if and only if the
  770. new value is after the old value.
  771. :raises TypeError: if `key` is not the one of the keys tracked by a StreamToken.
  772. """
  773. if key == StreamKeyType.ROOM:
  774. new_token = self.copy_and_replace(
  775. StreamKeyType.ROOM, self.room_key.copy_and_advance(new_value)
  776. )
  777. return new_token
  778. elif key == StreamKeyType.RECEIPT:
  779. new_token = self.copy_and_replace(
  780. StreamKeyType.RECEIPT, self.receipt_key.copy_and_advance(new_value)
  781. )
  782. return new_token
  783. new_token = self.copy_and_replace(key, new_value)
  784. new_id = new_token.get_field(key)
  785. old_id = self.get_field(key)
  786. if old_id < new_id:
  787. return new_token
  788. else:
  789. return self
  790. def copy_and_replace(self, key: StreamKeyType, new_value: Any) -> "StreamToken":
  791. return attr.evolve(self, **{key.value: new_value})
  792. @overload
  793. def get_field(self, key: Literal[StreamKeyType.ROOM]) -> RoomStreamToken:
  794. ...
  795. @overload
  796. def get_field(self, key: Literal[StreamKeyType.RECEIPT]) -> MultiWriterStreamToken:
  797. ...
  798. @overload
  799. def get_field(
  800. self,
  801. key: Literal[
  802. StreamKeyType.ACCOUNT_DATA,
  803. StreamKeyType.DEVICE_LIST,
  804. StreamKeyType.PRESENCE,
  805. StreamKeyType.PUSH_RULES,
  806. StreamKeyType.TO_DEVICE,
  807. StreamKeyType.TYPING,
  808. StreamKeyType.UN_PARTIAL_STATED_ROOMS,
  809. ],
  810. ) -> int:
  811. ...
  812. @overload
  813. def get_field(
  814. self, key: StreamKeyType
  815. ) -> Union[int, RoomStreamToken, MultiWriterStreamToken]:
  816. ...
  817. def get_field(
  818. self, key: StreamKeyType
  819. ) -> Union[int, RoomStreamToken, MultiWriterStreamToken]:
  820. """Returns the stream ID for the given key."""
  821. return getattr(self, key.value)
  822. StreamToken.START = StreamToken(
  823. RoomStreamToken(stream=0), 0, 0, MultiWriterStreamToken(stream=0), 0, 0, 0, 0, 0, 0
  824. )
  825. @attr.s(slots=True, frozen=True, auto_attribs=True)
  826. class PersistedPosition:
  827. """Position of a newly persisted row with instance that persisted it."""
  828. instance_name: str
  829. stream: int
  830. def persisted_after(self, token: AbstractMultiWriterStreamToken) -> bool:
  831. return token.get_stream_pos_for_instance(self.instance_name) < self.stream
  832. @attr.s(slots=True, frozen=True, auto_attribs=True)
  833. class PersistedEventPosition(PersistedPosition):
  834. """Position of a newly persisted event with instance that persisted it.
  835. This can be used to test whether the event is persisted before or after a
  836. RoomStreamToken.
  837. """
  838. def to_room_stream_token(self) -> RoomStreamToken:
  839. """Converts the position to a room stream token such that events
  840. persisted in the same room after this position will be after the
  841. returned `RoomStreamToken`.
  842. Note: no guarantees are made about ordering w.r.t. events in other
  843. rooms.
  844. """
  845. # Doing the naive thing satisfies the desired properties described in
  846. # the docstring.
  847. return RoomStreamToken(stream=self.stream)
  848. @attr.s(slots=True, frozen=True, auto_attribs=True)
  849. class ThirdPartyInstanceID:
  850. appservice_id: Optional[str]
  851. network_id: Optional[str]
  852. # Deny iteration because it will bite you if you try to create a singleton
  853. # set by:
  854. # users = set(user)
  855. def __iter__(self) -> NoReturn:
  856. raise ValueError("Attempted to iterate a %s" % (type(self).__name__,))
  857. # Because this class is a frozen class, it is deeply immutable.
  858. def __copy__(self) -> "ThirdPartyInstanceID":
  859. return self
  860. def __deepcopy__(self, memo: Dict[str, object]) -> "ThirdPartyInstanceID":
  861. return self
  862. @classmethod
  863. def from_string(cls, s: str) -> "ThirdPartyInstanceID":
  864. bits = s.split("|", 2)
  865. if len(bits) != 2:
  866. raise SynapseError(400, "Invalid ID %r" % (s,))
  867. return cls(appservice_id=bits[0], network_id=bits[1])
  868. def to_string(self) -> str:
  869. return "%s|%s" % (self.appservice_id, self.network_id)
  870. __str__ = to_string
  871. @attr.s(slots=True, frozen=True, auto_attribs=True)
  872. class ReadReceipt:
  873. """Information about a read-receipt"""
  874. room_id: str
  875. receipt_type: str
  876. user_id: str
  877. event_ids: List[str]
  878. thread_id: Optional[str]
  879. data: JsonDict
  880. @attr.s(slots=True, frozen=True, auto_attribs=True)
  881. class DeviceListUpdates:
  882. """
  883. An object containing a diff of information regarding other users' device lists, intended for
  884. a recipient to carry out device list tracking.
  885. Attributes:
  886. changed: A set of users whose device lists have changed recently.
  887. left: A set of users who the recipient no longer needs to track the device lists of.
  888. Typically when those users no longer share any end-to-end encryption enabled rooms.
  889. """
  890. # We need to use a factory here, otherwise `set` is not evaluated at
  891. # object instantiation, but instead at class definition instantiation.
  892. # The latter happening only once, thus always giving you the same sets
  893. # across multiple DeviceListUpdates instances.
  894. # Also see: don't define mutable default arguments.
  895. changed: Set[str] = attr.ib(factory=set)
  896. left: Set[str] = attr.ib(factory=set)
  897. def __bool__(self) -> bool:
  898. return bool(self.changed or self.left)
  899. def get_verify_key_from_cross_signing_key(
  900. key_info: Mapping[str, Any]
  901. ) -> Tuple[str, VerifyKey]:
  902. """Get the key ID and signedjson verify key from a cross-signing key dict
  903. Args:
  904. key_info: a cross-signing key dict, which must have a "keys"
  905. property that has exactly one item in it
  906. Returns:
  907. the key ID and verify key for the cross-signing key
  908. """
  909. # make sure that a `keys` field is provided
  910. if "keys" not in key_info:
  911. raise ValueError("Invalid key")
  912. keys = key_info["keys"]
  913. # and that it contains exactly one key
  914. if len(keys) == 1:
  915. key_id, key_data = next(iter(keys.items()))
  916. return key_id, decode_verify_key_bytes(key_id, decode_base64(key_data))
  917. else:
  918. raise ValueError("Invalid key")
  919. @attr.s(auto_attribs=True, frozen=True, slots=True)
  920. class UserInfo:
  921. """Holds information about a user. Result of get_user_by_id.
  922. Attributes:
  923. user_id: ID of the user.
  924. appservice_id: Application service ID that created this user.
  925. consent_server_notice_sent: Version of policy documents the user has been sent.
  926. consent_version: Version of policy documents the user has consented to.
  927. consent_ts: Time the user consented
  928. creation_ts: Creation timestamp of the user.
  929. is_admin: True if the user is an admin.
  930. is_deactivated: True if the user has been deactivated.
  931. is_guest: True if the user is a guest user.
  932. is_shadow_banned: True if the user has been shadow-banned.
  933. user_type: User type (None for normal user, 'support' and 'bot' other options).
  934. approved: If the user has been "approved" to register on the server.
  935. locked: Whether the user's account has been locked
  936. """
  937. user_id: UserID
  938. appservice_id: Optional[int]
  939. consent_server_notice_sent: Optional[str]
  940. consent_version: Optional[str]
  941. consent_ts: Optional[int]
  942. user_type: Optional[str]
  943. creation_ts: int
  944. is_admin: bool
  945. is_deactivated: bool
  946. is_guest: bool
  947. is_shadow_banned: bool
  948. approved: bool
  949. locked: bool
  950. class UserProfile(TypedDict):
  951. user_id: str
  952. display_name: Optional[str]
  953. avatar_url: Optional[str]
  954. @attr.s(auto_attribs=True, frozen=True, slots=True)
  955. class RetentionPolicy:
  956. min_lifetime: Optional[int] = None
  957. max_lifetime: Optional[int] = None
  958. class TaskStatus(str, Enum):
  959. """Status of a scheduled task"""
  960. # Task is scheduled but not active
  961. SCHEDULED = "scheduled"
  962. # Task is active and probably running, and if not
  963. # will be run on next scheduler loop run
  964. ACTIVE = "active"
  965. # Task has completed successfully
  966. COMPLETE = "complete"
  967. # Task is over and either returned a failed status, or had an exception
  968. FAILED = "failed"
  969. @attr.s(auto_attribs=True, frozen=True, slots=True)
  970. class ScheduledTask:
  971. """Description of a scheduled task"""
  972. # Id used to identify the task
  973. id: str
  974. # Name of the action to be run by this task
  975. action: str
  976. # Current status of this task
  977. status: TaskStatus
  978. # If the status is SCHEDULED then this represents when it should be launched,
  979. # otherwise it represents the last time this task got a change of state.
  980. # In milliseconds since epoch in system time timezone, usually UTC.
  981. timestamp: int
  982. # Optionally bind a task to some resource id for easy retrieval
  983. resource_id: Optional[str]
  984. # Optional parameters that will be passed to the function ran by the task
  985. params: Optional[JsonMapping]
  986. # Optional result that can be updated by the running task
  987. result: Optional[JsonMapping]
  988. # Optional error that should be assigned a value when the status is FAILED
  989. error: Optional[str]