選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

716 行
24 KiB

  1. # Copyright 2017 Vector Creations Ltd
  2. # Copyright 2019 New Vector 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. import heapq
  16. import logging
  17. from typing import (
  18. TYPE_CHECKING,
  19. Any,
  20. Awaitable,
  21. Callable,
  22. List,
  23. Optional,
  24. Tuple,
  25. TypeVar,
  26. )
  27. import attr
  28. from synapse.api.constants import AccountDataTypes
  29. from synapse.replication.http.streams import ReplicationGetStreamUpdates
  30. if TYPE_CHECKING:
  31. from synapse.server import HomeServer
  32. from synapse.storage.util.id_generators import AbstractStreamIdGenerator
  33. logger = logging.getLogger(__name__)
  34. # the number of rows to request from an update_function.
  35. _STREAM_UPDATE_TARGET_ROW_COUNT = 100
  36. # Some type aliases to make things a bit easier.
  37. # A stream position token
  38. Token = int
  39. # The type of a stream update row, after JSON deserialisation, but before
  40. # parsing with Stream.parse_row (which turns it into a `ROW_TYPE`). Normally it's
  41. # just a row from a database query, though this is dependent on the stream in question.
  42. #
  43. StreamRow = TypeVar("StreamRow", bound=Tuple)
  44. # The type returned by the update_function of a stream, as well as get_updates(),
  45. # get_updates_since, etc.
  46. #
  47. # It consists of a triplet `(updates, new_last_token, limited)`, where:
  48. # * `updates` is a list of `(token, row)` entries.
  49. # * `new_last_token` is the new position in stream.
  50. # * `limited` is whether there are more updates to fetch.
  51. #
  52. StreamUpdateResult = Tuple[List[Tuple[Token, StreamRow]], Token, bool]
  53. # The type of an update_function for a stream
  54. #
  55. # The arguments are:
  56. #
  57. # * instance_name: the writer of the stream
  58. # * from_token: the previous stream token: the starting point for fetching the
  59. # updates
  60. # * to_token: the new stream token: the point to get updates up to
  61. # * target_row_count: a target for the number of rows to be returned.
  62. #
  63. # The update_function is expected to return up to _approximately_ target_row_count rows.
  64. # If there are more updates available, it should set `limited` in the result, and
  65. # it will be called again to get the next batch.
  66. #
  67. UpdateFunction = Callable[[str, Token, Token, int], Awaitable[StreamUpdateResult]]
  68. class Stream:
  69. """Base class for the streams.
  70. Provides a `get_updates()` function that returns new updates since the last
  71. time it was called.
  72. """
  73. NAME: str # The name of the stream
  74. # The type of the row. Used by the default impl of parse_row.
  75. ROW_TYPE: Any = None
  76. @classmethod
  77. def parse_row(cls, row: StreamRow) -> Any:
  78. """Parse a row received over replication
  79. By default, assumes that the row data is an array object and passes its contents
  80. to the constructor of the ROW_TYPE for this stream.
  81. Args:
  82. row: row data from the incoming RDATA command, after json decoding
  83. Returns:
  84. ROW_TYPE object for this stream
  85. """
  86. return cls.ROW_TYPE(*row)
  87. def __init__(
  88. self,
  89. local_instance_name: str,
  90. update_function: UpdateFunction,
  91. ):
  92. """Instantiate a Stream
  93. `update_function` is called to get updates for this stream between a
  94. pair of stream tokens. See the `UpdateFunction` type definition for more
  95. info.
  96. Args:
  97. local_instance_name: The instance name of the current process
  98. current_token_function: callback to get the current token, as above
  99. update_function: callback go get stream updates, as above
  100. """
  101. self.local_instance_name = local_instance_name
  102. self.update_function = update_function
  103. # The token from which we last asked for updates
  104. self.last_token = self.current_token(self.local_instance_name)
  105. def current_token(self, instance_name: str) -> Token:
  106. """This takes an instance name, which is a writer to
  107. the stream, and returns the position in the stream of the writer (as
  108. viewed from the current process).
  109. """
  110. # We can't make this an abstract class as it makes mypy unhappy.
  111. raise NotImplementedError()
  112. def minimal_local_current_token(self) -> Token:
  113. """Tries to return a minimal current token for the local instance,
  114. i.e. for writers this would be the last successful write.
  115. If local instance is not a writer (or has written yet) then falls back
  116. to returning the normal "current token".
  117. """
  118. raise NotImplementedError()
  119. def can_discard_position(
  120. self, instance_name: str, prev_token: int, new_token: int
  121. ) -> bool:
  122. """Whether or not a position command for this stream can be discarded.
  123. Useful for streams that can never go backwards and where we already know
  124. the stream ID for the instance has advanced.
  125. """
  126. return False
  127. def discard_updates_and_advance(self) -> None:
  128. """Called when the stream should advance but the updates would be discarded,
  129. e.g. when there are no currently connected workers.
  130. """
  131. self.last_token = self.current_token(self.local_instance_name)
  132. async def get_updates(self) -> StreamUpdateResult:
  133. """Gets all updates since the last time this function was called (or
  134. since the stream was constructed if it hadn't been called before).
  135. Returns:
  136. A triplet `(updates, new_last_token, limited)`, where `updates` is
  137. a list of `(token, row)` entries, `new_last_token` is the new
  138. position in stream (ie the highest token returned in the updates),
  139. and `limited` is whether there are more updates to fetch.
  140. """
  141. current_token = self.current_token(self.local_instance_name)
  142. # If the minimum current token for the local instance is less than or
  143. # equal to the last thing we published, we know that there are no
  144. # updates.
  145. if self.last_token >= self.minimal_local_current_token():
  146. self.last_token = current_token
  147. return [], current_token, False
  148. updates, current_token, limited = await self.get_updates_since(
  149. self.local_instance_name, self.last_token, current_token
  150. )
  151. self.last_token = current_token
  152. return updates, current_token, limited
  153. async def get_updates_since(
  154. self, instance_name: str, from_token: Token, upto_token: Token
  155. ) -> StreamUpdateResult:
  156. """Like get_updates except allows specifying from when we should
  157. stream updates
  158. Returns:
  159. A triplet `(updates, new_last_token, limited)`, where `updates` is
  160. a list of `(token, row)` entries, `new_last_token` is the new
  161. position in stream, and `limited` is whether there are more updates
  162. to fetch.
  163. """
  164. from_token = int(from_token)
  165. if from_token == upto_token:
  166. return [], upto_token, False
  167. updates, upto_token, limited = await self.update_function(
  168. instance_name,
  169. from_token,
  170. upto_token,
  171. _STREAM_UPDATE_TARGET_ROW_COUNT,
  172. )
  173. return updates, upto_token, limited
  174. class _StreamFromIdGen(Stream):
  175. """Helper class for simple streams that use a stream ID generator"""
  176. def __init__(
  177. self,
  178. local_instance_name: str,
  179. update_function: UpdateFunction,
  180. stream_id_gen: "AbstractStreamIdGenerator",
  181. ):
  182. self._stream_id_gen = stream_id_gen
  183. super().__init__(local_instance_name, update_function)
  184. def current_token(self, instance_name: str) -> Token:
  185. return self._stream_id_gen.get_current_token_for_writer(instance_name)
  186. def minimal_local_current_token(self) -> Token:
  187. return self._stream_id_gen.get_minimal_local_current_token()
  188. def can_discard_position(
  189. self, instance_name: str, prev_token: int, new_token: int
  190. ) -> bool:
  191. # These streams can't go backwards, so we know we can ignore any
  192. # positions where the tokens are from before the current token.
  193. return new_token <= self.current_token(instance_name)
  194. def current_token_without_instance(
  195. current_token: Callable[[], int]
  196. ) -> Callable[[str], int]:
  197. """Takes a current token callback function for a single writer stream
  198. that doesn't take an instance name parameter and wraps it in a function that
  199. does accept an instance name parameter but ignores it.
  200. """
  201. return lambda instance_name: current_token()
  202. def make_http_update_function(hs: "HomeServer", stream_name: str) -> UpdateFunction:
  203. """Makes a suitable function for use as an `update_function` that queries
  204. the master process for updates.
  205. """
  206. client = ReplicationGetStreamUpdates.make_client(hs)
  207. async def update_function(
  208. instance_name: str, from_token: int, upto_token: int, limit: int
  209. ) -> StreamUpdateResult:
  210. result = await client(
  211. instance_name=instance_name,
  212. stream_name=stream_name,
  213. from_token=from_token,
  214. upto_token=upto_token,
  215. )
  216. return result["updates"], result["upto_token"], result["limited"]
  217. return update_function
  218. class BackfillStream(Stream):
  219. """We fetched some old events and either we had never seen that event before
  220. or it went from being an outlier to not.
  221. """
  222. @attr.s(slots=True, frozen=True, auto_attribs=True)
  223. class BackfillStreamRow:
  224. event_id: str
  225. room_id: str
  226. type: str
  227. state_key: Optional[str]
  228. redacts: Optional[str]
  229. relates_to: Optional[str]
  230. NAME = "backfill"
  231. ROW_TYPE = BackfillStreamRow
  232. def __init__(self, hs: "HomeServer"):
  233. self.store = hs.get_datastores().main
  234. super().__init__(
  235. hs.get_instance_name(),
  236. self.store.get_all_new_backfill_event_rows,
  237. )
  238. def current_token(self, instance_name: str) -> Token:
  239. # The backfill stream over replication operates on *positive* numbers,
  240. # which means we need to negate it.
  241. return -self.store._backfill_id_gen.get_current_token_for_writer(instance_name)
  242. def minimal_local_current_token(self) -> Token:
  243. # The backfill stream over replication operates on *positive* numbers,
  244. # which means we need to negate it.
  245. return -self.store._backfill_id_gen.get_minimal_local_current_token()
  246. def can_discard_position(
  247. self, instance_name: str, prev_token: int, new_token: int
  248. ) -> bool:
  249. # Backfill stream can't go backwards, so we know we can ignore any
  250. # positions where the tokens are from before the current token.
  251. return new_token <= self.current_token(instance_name)
  252. class PresenceStream(_StreamFromIdGen):
  253. @attr.s(slots=True, frozen=True, auto_attribs=True)
  254. class PresenceStreamRow:
  255. user_id: str
  256. state: str
  257. last_active_ts: int
  258. last_federation_update_ts: int
  259. last_user_sync_ts: int
  260. status_msg: str
  261. currently_active: bool
  262. NAME = "presence"
  263. ROW_TYPE = PresenceStreamRow
  264. def __init__(self, hs: "HomeServer"):
  265. store = hs.get_datastores().main
  266. if hs.get_instance_name() in hs.config.worker.writers.presence:
  267. # on the presence writer, query the presence handler
  268. presence_handler = hs.get_presence_handler()
  269. from synapse.handlers.presence import PresenceHandler
  270. assert isinstance(presence_handler, PresenceHandler)
  271. update_function: UpdateFunction = presence_handler.get_all_presence_updates
  272. else:
  273. # Query presence writer process
  274. update_function = make_http_update_function(hs, self.NAME)
  275. super().__init__(
  276. hs.get_instance_name(), update_function, store._presence_id_gen
  277. )
  278. class PresenceFederationStream(Stream):
  279. """A stream used to send ad hoc presence updates over federation.
  280. Streams the remote destination and the user ID of the presence state to
  281. send.
  282. """
  283. @attr.s(slots=True, frozen=True, auto_attribs=True)
  284. class PresenceFederationStreamRow:
  285. destination: str
  286. user_id: str
  287. NAME = "presence_federation"
  288. ROW_TYPE = PresenceFederationStreamRow
  289. def __init__(self, hs: "HomeServer"):
  290. self._federation_queue = hs.get_presence_handler().get_federation_queue()
  291. super().__init__(
  292. hs.get_instance_name(),
  293. self._federation_queue.get_replication_rows,
  294. )
  295. def current_token(self, instance_name: str) -> Token:
  296. return self._federation_queue.get_current_token(instance_name)
  297. def minimal_local_current_token(self) -> Token:
  298. return self._federation_queue.get_current_token(self.local_instance_name)
  299. class TypingStream(Stream):
  300. @attr.s(slots=True, frozen=True, auto_attribs=True)
  301. class TypingStreamRow:
  302. """
  303. An entry in the typing stream.
  304. Describes all the users that are 'typing' right now in one room.
  305. When a user stops typing, it will be streamed as a new update with that
  306. user absent; you can think of the `user_ids` list as overwriting the
  307. entire list that was there previously.
  308. """
  309. # The room that this update is for.
  310. room_id: str
  311. # All the users that are 'typing' right now in the specified room.
  312. user_ids: List[str]
  313. NAME = "typing"
  314. ROW_TYPE = TypingStreamRow
  315. def __init__(self, hs: "HomeServer"):
  316. if hs.get_instance_name() in hs.config.worker.writers.typing:
  317. # On the writer, query the typing handler
  318. typing_writer_handler = hs.get_typing_writer_handler()
  319. update_function: Callable[
  320. [str, int, int, int], Awaitable[Tuple[List[Tuple[int, Any]], int, bool]]
  321. ] = typing_writer_handler.get_all_typing_updates
  322. self.current_token_function = typing_writer_handler.get_current_token
  323. else:
  324. # Query the typing writer process
  325. update_function = make_http_update_function(hs, self.NAME)
  326. self.current_token_function = hs.get_typing_handler().get_current_token
  327. super().__init__(
  328. hs.get_instance_name(),
  329. update_function,
  330. )
  331. def current_token(self, instance_name: str) -> Token:
  332. return self.current_token_function()
  333. def minimal_local_current_token(self) -> Token:
  334. return self.current_token_function()
  335. class ReceiptsStream(_StreamFromIdGen):
  336. @attr.s(slots=True, frozen=True, auto_attribs=True)
  337. class ReceiptsStreamRow:
  338. room_id: str
  339. receipt_type: str
  340. user_id: str
  341. event_id: str
  342. thread_id: Optional[str]
  343. data: dict
  344. NAME = "receipts"
  345. ROW_TYPE = ReceiptsStreamRow
  346. def __init__(self, hs: "HomeServer"):
  347. store = hs.get_datastores().main
  348. super().__init__(
  349. hs.get_instance_name(),
  350. store.get_all_updated_receipts,
  351. store._receipts_id_gen,
  352. )
  353. class PushRulesStream(_StreamFromIdGen):
  354. """A user has changed their push rules"""
  355. @attr.s(slots=True, frozen=True, auto_attribs=True)
  356. class PushRulesStreamRow:
  357. user_id: str
  358. NAME = "push_rules"
  359. ROW_TYPE = PushRulesStreamRow
  360. def __init__(self, hs: "HomeServer"):
  361. store = hs.get_datastores().main
  362. super().__init__(
  363. hs.get_instance_name(),
  364. store.get_all_push_rule_updates,
  365. store._push_rules_stream_id_gen,
  366. )
  367. class PushersStream(_StreamFromIdGen):
  368. """A user has added/changed/removed a pusher"""
  369. @attr.s(slots=True, frozen=True, auto_attribs=True)
  370. class PushersStreamRow:
  371. user_id: str
  372. app_id: str
  373. pushkey: str
  374. deleted: bool
  375. NAME = "pushers"
  376. ROW_TYPE = PushersStreamRow
  377. def __init__(self, hs: "HomeServer"):
  378. store = hs.get_datastores().main
  379. super().__init__(
  380. hs.get_instance_name(),
  381. store.get_all_updated_pushers_rows,
  382. store._pushers_id_gen,
  383. )
  384. class CachesStream(Stream):
  385. """A cache was invalidated on the master and no other stream would invalidate
  386. the cache on the workers
  387. """
  388. @attr.s(slots=True, frozen=True, auto_attribs=True)
  389. class CachesStreamRow:
  390. """Stream to inform workers they should invalidate their cache.
  391. Attributes:
  392. cache_func: Name of the cached function.
  393. keys: The entry in the cache to invalidate. If None then will
  394. invalidate all.
  395. invalidation_ts: Timestamp of when the invalidation took place.
  396. """
  397. cache_func: str
  398. keys: Optional[List[Any]]
  399. invalidation_ts: int
  400. NAME = "caches"
  401. ROW_TYPE = CachesStreamRow
  402. def __init__(self, hs: "HomeServer"):
  403. self.store = hs.get_datastores().main
  404. super().__init__(
  405. hs.get_instance_name(),
  406. self.store.get_all_updated_caches,
  407. )
  408. def current_token(self, instance_name: str) -> Token:
  409. return self.store.get_cache_stream_token_for_writer(instance_name)
  410. def minimal_local_current_token(self) -> Token:
  411. if self.store._cache_id_gen:
  412. return self.store._cache_id_gen.get_minimal_local_current_token()
  413. return self.current_token(self.local_instance_name)
  414. def can_discard_position(
  415. self, instance_name: str, prev_token: int, new_token: int
  416. ) -> bool:
  417. # Caches streams can't go backwards, so we know we can ignore any
  418. # positions where the tokens are from before the current token.
  419. return new_token <= self.current_token(instance_name)
  420. class DeviceListsStream(_StreamFromIdGen):
  421. """Either a user has updated their devices or a remote server needs to be
  422. told about a device update.
  423. """
  424. @attr.s(slots=True, frozen=True, auto_attribs=True)
  425. class DeviceListsStreamRow:
  426. entity: str
  427. # Indicates that a user has signed their own device with their user-signing key
  428. is_signature: bool
  429. NAME = "device_lists"
  430. ROW_TYPE = DeviceListsStreamRow
  431. def __init__(self, hs: "HomeServer"):
  432. self.store = hs.get_datastores().main
  433. super().__init__(
  434. hs.get_instance_name(),
  435. self._update_function,
  436. self.store._device_list_id_gen,
  437. )
  438. async def _update_function(
  439. self,
  440. instance_name: str,
  441. from_token: Token,
  442. current_token: Token,
  443. target_row_count: int,
  444. ) -> StreamUpdateResult:
  445. (
  446. device_updates,
  447. devices_to_token,
  448. devices_limited,
  449. ) = await self.store.get_all_device_list_changes_for_remotes(
  450. instance_name, from_token, current_token, target_row_count
  451. )
  452. (
  453. signatures_updates,
  454. signatures_to_token,
  455. signatures_limited,
  456. ) = await self.store.get_all_user_signature_changes_for_remotes(
  457. instance_name, from_token, current_token, target_row_count
  458. )
  459. upper_limit_token = current_token
  460. if devices_limited:
  461. upper_limit_token = min(upper_limit_token, devices_to_token)
  462. if signatures_limited:
  463. upper_limit_token = min(upper_limit_token, signatures_to_token)
  464. device_updates = [
  465. (stream_id, (entity, False))
  466. for stream_id, (entity,) in device_updates
  467. if stream_id <= upper_limit_token
  468. ]
  469. signatures_updates = [
  470. (stream_id, (entity, True))
  471. for stream_id, (entity,) in signatures_updates
  472. if stream_id <= upper_limit_token
  473. ]
  474. updates = list(
  475. heapq.merge(device_updates, signatures_updates, key=lambda row: row[0])
  476. )
  477. return updates, upper_limit_token, devices_limited or signatures_limited
  478. class ToDeviceStream(_StreamFromIdGen):
  479. """New to_device messages for a client"""
  480. @attr.s(slots=True, frozen=True, auto_attribs=True)
  481. class ToDeviceStreamRow:
  482. entity: str
  483. NAME = "to_device"
  484. ROW_TYPE = ToDeviceStreamRow
  485. def __init__(self, hs: "HomeServer"):
  486. store = hs.get_datastores().main
  487. super().__init__(
  488. hs.get_instance_name(),
  489. store.get_all_new_device_messages,
  490. store._to_device_msg_id_gen,
  491. )
  492. class AccountDataStream(_StreamFromIdGen):
  493. """Global or per room account data was changed"""
  494. @attr.s(slots=True, frozen=True, auto_attribs=True)
  495. class AccountDataStreamRow:
  496. user_id: str
  497. room_id: Optional[str]
  498. data_type: str
  499. NAME = "account_data"
  500. ROW_TYPE = AccountDataStreamRow
  501. def __init__(self, hs: "HomeServer"):
  502. self.store = hs.get_datastores().main
  503. super().__init__(
  504. hs.get_instance_name(),
  505. self._update_function,
  506. self.store._account_data_id_gen,
  507. )
  508. async def _update_function(
  509. self, instance_name: str, from_token: int, to_token: int, limit: int
  510. ) -> StreamUpdateResult:
  511. limited = False
  512. global_results = await self.store.get_updated_global_account_data(
  513. from_token, to_token, limit
  514. )
  515. # if the global results hit the limit, we'll need to limit the room results to
  516. # the same stream token.
  517. if len(global_results) >= limit:
  518. to_token = global_results[-1][0]
  519. limited = True
  520. room_results = await self.store.get_updated_room_account_data(
  521. from_token, to_token, limit
  522. )
  523. # likewise, if the room results hit the limit, limit the global results to
  524. # the same stream token.
  525. if len(room_results) >= limit:
  526. to_token = room_results[-1][0]
  527. limited = True
  528. tags, tag_to_token, tags_limited = await self.store.get_all_updated_tags(
  529. instance_name,
  530. from_token,
  531. to_token,
  532. limit,
  533. )
  534. # again, if the tag results hit the limit, limit the global results to
  535. # the same stream token.
  536. if tags_limited:
  537. to_token = tag_to_token
  538. limited = True
  539. # convert the global results to the right format, and limit them to the to_token
  540. # at the same time
  541. global_rows = (
  542. (stream_id, (user_id, None, account_data_type))
  543. for stream_id, user_id, account_data_type in global_results
  544. if stream_id <= to_token
  545. )
  546. room_rows = (
  547. (stream_id, (user_id, room_id, account_data_type))
  548. for stream_id, user_id, room_id, account_data_type in room_results
  549. if stream_id <= to_token
  550. )
  551. tag_rows = (
  552. (stream_id, (user_id, room_id, AccountDataTypes.TAG))
  553. for stream_id, user_id, room_id in tags
  554. if stream_id <= to_token
  555. )
  556. # We need to return a sorted list, so merge them together.
  557. #
  558. # Note: We order only by the stream ID to work around a bug where the
  559. # same stream ID could appear in both `global_rows` and `room_rows`,
  560. # leading to a comparison between the data tuples. The comparison could
  561. # fail due to attempting to compare the `room_id` which results in a
  562. # `TypeError` from comparing a `str` vs `None`.
  563. updates = list(
  564. heapq.merge(room_rows, global_rows, tag_rows, key=lambda row: row[0])
  565. )
  566. return updates, to_token, limited