appservice.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. # Copyright 2015, 2016 OpenMarket 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 TYPE_CHECKING, Collection, Dict, Iterable, List, Optional, Union
  16. from prometheus_client import Counter
  17. from twisted.internet import defer
  18. import synapse
  19. from synapse.api.constants import EventTypes
  20. from synapse.appservice import ApplicationService
  21. from synapse.events import EventBase
  22. from synapse.handlers.presence import format_user_presence_state
  23. from synapse.logging.context import make_deferred_yieldable, run_in_background
  24. from synapse.metrics import (
  25. event_processing_loop_counter,
  26. event_processing_loop_room_count,
  27. )
  28. from synapse.metrics.background_process_metrics import (
  29. run_as_background_process,
  30. wrap_as_background_process,
  31. )
  32. from synapse.storage.databases.main.directory import RoomAliasMapping
  33. from synapse.types import JsonDict, RoomAlias, RoomStreamToken, UserID
  34. from synapse.util.async_helpers import Linearizer
  35. from synapse.util.metrics import Measure
  36. if TYPE_CHECKING:
  37. from synapse.server import HomeServer
  38. logger = logging.getLogger(__name__)
  39. events_processed_counter = Counter("synapse_handlers_appservice_events_processed", "")
  40. class ApplicationServicesHandler:
  41. def __init__(self, hs: "HomeServer"):
  42. self.store = hs.get_datastores().main
  43. self.is_mine_id = hs.is_mine_id
  44. self.appservice_api = hs.get_application_service_api()
  45. self.scheduler = hs.get_application_service_scheduler()
  46. self.started_scheduler = False
  47. self.clock = hs.get_clock()
  48. self.notify_appservices = hs.config.appservice.notify_appservices
  49. self.event_sources = hs.get_event_sources()
  50. self._msc2409_to_device_messages_enabled = (
  51. hs.config.experimental.msc2409_to_device_messages_enabled
  52. )
  53. self.current_max = 0
  54. self.is_processing = False
  55. self._ephemeral_events_linearizer = Linearizer(
  56. name="appservice_ephemeral_events"
  57. )
  58. def notify_interested_services(self, max_token: RoomStreamToken) -> None:
  59. """Notifies (pushes) all application services interested in this event.
  60. Pushing is done asynchronously, so this method won't block for any
  61. prolonged length of time.
  62. """
  63. # We just use the minimum stream ordering and ignore the vector clock
  64. # component. This is safe to do as long as we *always* ignore the vector
  65. # clock components.
  66. current_id = max_token.stream
  67. services = self.store.get_app_services()
  68. if not services or not self.notify_appservices:
  69. return
  70. self.current_max = max(self.current_max, current_id)
  71. if self.is_processing:
  72. return
  73. # We only start a new background process if necessary rather than
  74. # optimistically (to cut down on overhead).
  75. self._notify_interested_services(max_token)
  76. @wrap_as_background_process("notify_interested_services")
  77. async def _notify_interested_services(self, max_token: RoomStreamToken) -> None:
  78. with Measure(self.clock, "notify_interested_services"):
  79. self.is_processing = True
  80. try:
  81. limit = 100
  82. upper_bound = -1
  83. while upper_bound < self.current_max:
  84. (
  85. upper_bound,
  86. events,
  87. ) = await self.store.get_new_events_for_appservice(
  88. self.current_max, limit
  89. )
  90. events_by_room: Dict[str, List[EventBase]] = {}
  91. for event in events:
  92. events_by_room.setdefault(event.room_id, []).append(event)
  93. async def handle_event(event: EventBase) -> None:
  94. # Gather interested services
  95. services = await self._get_services_for_event(event)
  96. if len(services) == 0:
  97. return # no services need notifying
  98. # Do we know this user exists? If not, poke the user
  99. # query API for all services which match that user regex.
  100. # This needs to block as these user queries need to be
  101. # made BEFORE pushing the event.
  102. await self._check_user_exists(event.sender)
  103. if event.type == EventTypes.Member:
  104. await self._check_user_exists(event.state_key)
  105. if not self.started_scheduler:
  106. async def start_scheduler() -> None:
  107. try:
  108. await self.scheduler.start()
  109. except Exception:
  110. logger.error("Application Services Failure")
  111. run_as_background_process("as_scheduler", start_scheduler)
  112. self.started_scheduler = True
  113. # Fork off pushes to these services
  114. for service in services:
  115. self.scheduler.enqueue_for_appservice(
  116. service, events=[event]
  117. )
  118. now = self.clock.time_msec()
  119. ts = await self.store.get_received_ts(event.event_id)
  120. assert ts is not None
  121. synapse.metrics.event_processing_lag_by_event.labels(
  122. "appservice_sender"
  123. ).observe((now - ts) / 1000)
  124. async def handle_room_events(events: Iterable[EventBase]) -> None:
  125. for event in events:
  126. await handle_event(event)
  127. await make_deferred_yieldable(
  128. defer.gatherResults(
  129. [
  130. run_in_background(handle_room_events, evs)
  131. for evs in events_by_room.values()
  132. ],
  133. consumeErrors=True,
  134. )
  135. )
  136. await self.store.set_appservice_last_pos(upper_bound)
  137. synapse.metrics.event_processing_positions.labels(
  138. "appservice_sender"
  139. ).set(upper_bound)
  140. events_processed_counter.inc(len(events))
  141. event_processing_loop_room_count.labels("appservice_sender").inc(
  142. len(events_by_room)
  143. )
  144. event_processing_loop_counter.labels("appservice_sender").inc()
  145. if events:
  146. now = self.clock.time_msec()
  147. ts = await self.store.get_received_ts(events[-1].event_id)
  148. assert ts is not None
  149. synapse.metrics.event_processing_lag.labels(
  150. "appservice_sender"
  151. ).set(now - ts)
  152. synapse.metrics.event_processing_last_ts.labels(
  153. "appservice_sender"
  154. ).set(ts)
  155. finally:
  156. self.is_processing = False
  157. def notify_interested_services_ephemeral(
  158. self,
  159. stream_key: str,
  160. new_token: Union[int, RoomStreamToken],
  161. users: Collection[Union[str, UserID]],
  162. ) -> None:
  163. """
  164. This is called by the notifier in the background when an ephemeral event is handled
  165. by the homeserver.
  166. This will determine which appservices are interested in the event, and submit them.
  167. Args:
  168. stream_key: The stream the event came from.
  169. `stream_key` can be "typing_key", "receipt_key", "presence_key" or
  170. "to_device_key". Any other value for `stream_key` will cause this function
  171. to return early.
  172. Ephemeral events will only be pushed to appservices that have opted into
  173. receiving them by setting `push_ephemeral` to true in their registration
  174. file. Note that while MSC2409 is experimental, this option is called
  175. `de.sorunome.msc2409.push_ephemeral`.
  176. Appservices will only receive ephemeral events that fall within their
  177. registered user and room namespaces.
  178. new_token: The stream token of the event.
  179. users: The users that should be informed of the new event, if any.
  180. """
  181. if not self.notify_appservices:
  182. return
  183. # Notify appservices of updates in ephemeral event streams.
  184. # Only the following streams are currently supported.
  185. # FIXME: We should use constants for these values.
  186. if stream_key not in (
  187. "typing_key",
  188. "receipt_key",
  189. "presence_key",
  190. "to_device_key",
  191. ):
  192. return
  193. # Assert that new_token is an integer (and not a RoomStreamToken).
  194. # All of the supported streams that this function handles use an
  195. # integer to track progress (rather than a RoomStreamToken - a
  196. # vector clock implementation) as they don't support multiple
  197. # stream writers.
  198. #
  199. # As a result, we simply assert that new_token is an integer.
  200. # If we do end up needing to pass a RoomStreamToken down here
  201. # in the future, using RoomStreamToken.stream (the minimum stream
  202. # position) to convert to an ascending integer value should work.
  203. # Additional context: https://github.com/matrix-org/synapse/pull/11137
  204. assert isinstance(new_token, int)
  205. # Ignore to-device messages if the feature flag is not enabled
  206. if (
  207. stream_key == "to_device_key"
  208. and not self._msc2409_to_device_messages_enabled
  209. ):
  210. return
  211. # Check whether there are any appservices which have registered to receive
  212. # ephemeral events.
  213. #
  214. # Note that whether these events are actually relevant to these appservices
  215. # is decided later on.
  216. services = [
  217. service
  218. for service in self.store.get_app_services()
  219. if service.supports_ephemeral
  220. ]
  221. if not services:
  222. # Bail out early if none of the target appservices have explicitly registered
  223. # to receive these ephemeral events.
  224. return
  225. # We only start a new background process if necessary rather than
  226. # optimistically (to cut down on overhead).
  227. self._notify_interested_services_ephemeral(
  228. services, stream_key, new_token, users
  229. )
  230. @wrap_as_background_process("notify_interested_services_ephemeral")
  231. async def _notify_interested_services_ephemeral(
  232. self,
  233. services: List[ApplicationService],
  234. stream_key: str,
  235. new_token: int,
  236. users: Collection[Union[str, UserID]],
  237. ) -> None:
  238. logger.debug("Checking interested services for %s", stream_key)
  239. with Measure(self.clock, "notify_interested_services_ephemeral"):
  240. for service in services:
  241. if stream_key == "typing_key":
  242. # Note that we don't persist the token (via set_appservice_stream_type_pos)
  243. # for typing_key due to performance reasons and due to their highly
  244. # ephemeral nature.
  245. #
  246. # Instead we simply grab the latest typing updates in _handle_typing
  247. # and, if they apply to this application service, send it off.
  248. events = await self._handle_typing(service, new_token)
  249. if events:
  250. self.scheduler.enqueue_for_appservice(service, ephemeral=events)
  251. continue
  252. # Since we read/update the stream position for this AS/stream
  253. with (
  254. await self._ephemeral_events_linearizer.queue(
  255. (service.id, stream_key)
  256. )
  257. ):
  258. if stream_key == "receipt_key":
  259. events = await self._handle_receipts(service, new_token)
  260. self.scheduler.enqueue_for_appservice(service, ephemeral=events)
  261. # Persist the latest handled stream token for this appservice
  262. await self.store.set_appservice_stream_type_pos(
  263. service, "read_receipt", new_token
  264. )
  265. elif stream_key == "presence_key":
  266. events = await self._handle_presence(service, users, new_token)
  267. self.scheduler.enqueue_for_appservice(service, ephemeral=events)
  268. # Persist the latest handled stream token for this appservice
  269. await self.store.set_appservice_stream_type_pos(
  270. service, "presence", new_token
  271. )
  272. elif stream_key == "to_device_key":
  273. # Retrieve a list of to-device message events, as well as the
  274. # maximum stream token of the messages we were able to retrieve.
  275. to_device_messages = await self._get_to_device_messages(
  276. service, new_token, users
  277. )
  278. self.scheduler.enqueue_for_appservice(
  279. service, to_device_messages=to_device_messages
  280. )
  281. # Persist the latest handled stream token for this appservice
  282. await self.store.set_appservice_stream_type_pos(
  283. service, "to_device", new_token
  284. )
  285. async def _handle_typing(
  286. self, service: ApplicationService, new_token: int
  287. ) -> List[JsonDict]:
  288. """
  289. Return the typing events since the given stream token that the given application
  290. service should receive.
  291. First fetch all typing events between the given typing stream token (non-inclusive)
  292. and the latest typing event stream token (inclusive). Then return only those typing
  293. events that the given application service may be interested in.
  294. Args:
  295. service: The application service to check for which events it should receive.
  296. new_token: A typing event stream token.
  297. Returns:
  298. A list of JSON dictionaries containing data derived from the typing events that
  299. should be sent to the given application service.
  300. """
  301. typing_source = self.event_sources.sources.typing
  302. # Get the typing events from just before current
  303. typing, _ = await typing_source.get_new_events_as(
  304. service=service,
  305. # For performance reasons, we don't persist the previous
  306. # token in the DB and instead fetch the latest typing event
  307. # for appservices.
  308. # TODO: It'd likely be more efficient to simply fetch the
  309. # typing event with the given 'new_token' stream token and
  310. # check if the given service was interested, rather than
  311. # iterating over all typing events and only grabbing the
  312. # latest few.
  313. from_key=new_token - 1,
  314. )
  315. return typing
  316. async def _handle_receipts(
  317. self, service: ApplicationService, new_token: Optional[int]
  318. ) -> List[JsonDict]:
  319. """
  320. Return the latest read receipts that the given application service should receive.
  321. First fetch all read receipts between the last receipt stream token that this
  322. application service should have previously received (non-inclusive) and the
  323. latest read receipt stream token (inclusive). Then from that set, return only
  324. those read receipts that the given application service may be interested in.
  325. Args:
  326. service: The application service to check for which events it should receive.
  327. new_token: A receipts event stream token. Purely used to double-check that the
  328. from_token we pull from the database isn't greater than or equal to this
  329. token. Prevents accidentally duplicating work.
  330. Returns:
  331. A list of JSON dictionaries containing data derived from the read receipts that
  332. should be sent to the given application service.
  333. """
  334. from_key = await self.store.get_type_stream_id_for_appservice(
  335. service, "read_receipt"
  336. )
  337. if new_token is not None and new_token <= from_key:
  338. logger.debug(
  339. "Rejecting token lower than or equal to stored: %s" % (new_token,)
  340. )
  341. return []
  342. receipts_source = self.event_sources.sources.receipt
  343. receipts, _ = await receipts_source.get_new_events_as(
  344. service=service, from_key=from_key
  345. )
  346. return receipts
  347. async def _handle_presence(
  348. self,
  349. service: ApplicationService,
  350. users: Collection[Union[str, UserID]],
  351. new_token: Optional[int],
  352. ) -> List[JsonDict]:
  353. """
  354. Return the latest presence updates that the given application service should receive.
  355. First, filter the given users list to those that the application service is
  356. interested in. Then retrieve the latest presence updates since the
  357. the last-known previously received presence stream token for the given
  358. application service. Return those presence updates.
  359. Args:
  360. service: The application service that ephemeral events are being sent to.
  361. users: The users that should receive the presence update.
  362. new_token: A presence update stream token. Purely used to double-check that the
  363. from_token we pull from the database isn't greater than or equal to this
  364. token. Prevents accidentally duplicating work.
  365. Returns:
  366. A list of json dictionaries containing data derived from the presence events
  367. that should be sent to the given application service.
  368. """
  369. events: List[JsonDict] = []
  370. presence_source = self.event_sources.sources.presence
  371. from_key = await self.store.get_type_stream_id_for_appservice(
  372. service, "presence"
  373. )
  374. if new_token is not None and new_token <= from_key:
  375. logger.debug(
  376. "Rejecting token lower than or equal to stored: %s" % (new_token,)
  377. )
  378. return []
  379. for user in users:
  380. if isinstance(user, str):
  381. user = UserID.from_string(user)
  382. interested = await service.is_interested_in_presence(user, self.store)
  383. if not interested:
  384. continue
  385. presence_events, _ = await presence_source.get_new_events(
  386. user=user,
  387. from_key=from_key,
  388. )
  389. time_now = self.clock.time_msec()
  390. events.extend(
  391. {
  392. "type": "m.presence",
  393. "sender": event.user_id,
  394. "content": format_user_presence_state(
  395. event, time_now, include_user_id=False
  396. ),
  397. }
  398. for event in presence_events
  399. )
  400. return events
  401. async def _get_to_device_messages(
  402. self,
  403. service: ApplicationService,
  404. new_token: int,
  405. users: Collection[Union[str, UserID]],
  406. ) -> List[JsonDict]:
  407. """
  408. Given an application service, determine which events it should receive
  409. from those between the last-recorded to-device message stream token for this
  410. appservice and the given stream token.
  411. Args:
  412. service: The application service to check for which events it should receive.
  413. new_token: The latest to-device event stream token.
  414. users: The users to be notified for the new to-device messages
  415. (ie, the recipients of the messages).
  416. Returns:
  417. A list of JSON dictionaries containing data derived from the to-device events
  418. that should be sent to the given application service.
  419. """
  420. # Get the stream token that this application service has processed up until
  421. from_key = await self.store.get_type_stream_id_for_appservice(
  422. service, "to_device"
  423. )
  424. # Filter out users that this appservice is not interested in
  425. users_appservice_is_interested_in: List[str] = []
  426. for user in users:
  427. # FIXME: We should do this farther up the call stack. We currently repeat
  428. # this operation in _handle_presence.
  429. if isinstance(user, UserID):
  430. user = user.to_string()
  431. if service.is_interested_in_user(user):
  432. users_appservice_is_interested_in.append(user)
  433. if not users_appservice_is_interested_in:
  434. # Return early if the AS was not interested in any of these users
  435. return []
  436. # Retrieve the to-device messages for each user
  437. recipient_device_to_messages = await self.store.get_messages_for_user_devices(
  438. users_appservice_is_interested_in,
  439. from_key,
  440. new_token,
  441. )
  442. # According to MSC2409, we'll need to add 'to_user_id' and 'to_device_id' fields
  443. # to the event JSON so that the application service will know which user/device
  444. # combination this messages was intended for.
  445. #
  446. # So we mangle this dict into a flat list of to-device messages with the relevant
  447. # user ID and device ID embedded inside each message dict.
  448. message_payload: List[JsonDict] = []
  449. for (
  450. user_id,
  451. device_id,
  452. ), messages in recipient_device_to_messages.items():
  453. for message_json in messages:
  454. # Remove 'message_id' from the to-device message, as it's an internal ID
  455. message_json.pop("message_id", None)
  456. message_payload.append(
  457. {
  458. "to_user_id": user_id,
  459. "to_device_id": device_id,
  460. **message_json,
  461. }
  462. )
  463. return message_payload
  464. async def query_user_exists(self, user_id: str) -> bool:
  465. """Check if any application service knows this user_id exists.
  466. Args:
  467. user_id: The user to query if they exist on any AS.
  468. Returns:
  469. True if this user exists on at least one application service.
  470. """
  471. user_query_services = self._get_services_for_user(user_id=user_id)
  472. for user_service in user_query_services:
  473. is_known_user = await self.appservice_api.query_user(user_service, user_id)
  474. if is_known_user:
  475. return True
  476. return False
  477. async def query_room_alias_exists(
  478. self, room_alias: RoomAlias
  479. ) -> Optional[RoomAliasMapping]:
  480. """Check if an application service knows this room alias exists.
  481. Args:
  482. room_alias: The room alias to query.
  483. Returns:
  484. RoomAliasMapping or None if no association can be found.
  485. """
  486. room_alias_str = room_alias.to_string()
  487. services = self.store.get_app_services()
  488. alias_query_services = [
  489. s for s in services if (s.is_interested_in_alias(room_alias_str))
  490. ]
  491. for alias_service in alias_query_services:
  492. is_known_alias = await self.appservice_api.query_alias(
  493. alias_service, room_alias_str
  494. )
  495. if is_known_alias:
  496. # the alias exists now so don't query more ASes.
  497. return await self.store.get_association_from_room_alias(room_alias)
  498. return None
  499. async def query_3pe(
  500. self, kind: str, protocol: str, fields: Dict[bytes, List[bytes]]
  501. ) -> List[JsonDict]:
  502. services = self._get_services_for_3pn(protocol)
  503. results = await make_deferred_yieldable(
  504. defer.DeferredList(
  505. [
  506. run_in_background(
  507. self.appservice_api.query_3pe, service, kind, protocol, fields
  508. )
  509. for service in services
  510. ],
  511. consumeErrors=True,
  512. )
  513. )
  514. ret = []
  515. for (success, result) in results:
  516. if success:
  517. ret.extend(result)
  518. return ret
  519. async def get_3pe_protocols(
  520. self, only_protocol: Optional[str] = None
  521. ) -> Dict[str, JsonDict]:
  522. services = self.store.get_app_services()
  523. protocols: Dict[str, List[JsonDict]] = {}
  524. # Collect up all the individual protocol responses out of the ASes
  525. for s in services:
  526. for p in s.protocols:
  527. if only_protocol is not None and p != only_protocol:
  528. continue
  529. if p not in protocols:
  530. protocols[p] = []
  531. info = await self.appservice_api.get_3pe_protocol(s, p)
  532. if info is not None:
  533. protocols[p].append(info)
  534. def _merge_instances(infos: List[JsonDict]) -> JsonDict:
  535. # Merge the 'instances' lists of multiple results, but just take
  536. # the other fields from the first as they ought to be identical
  537. # copy the result so as not to corrupt the cached one
  538. combined = dict(infos[0])
  539. combined["instances"] = list(combined["instances"])
  540. for info in infos[1:]:
  541. combined["instances"].extend(info["instances"])
  542. return combined
  543. return {
  544. p: _merge_instances(protocols[p]) for p in protocols.keys() if protocols[p]
  545. }
  546. async def _get_services_for_event(
  547. self, event: EventBase
  548. ) -> List[ApplicationService]:
  549. """Retrieve a list of application services interested in this event.
  550. Args:
  551. event: The event to check.
  552. Returns:
  553. A list of services interested in this event based on the service regex.
  554. """
  555. services = self.store.get_app_services()
  556. # we can't use a list comprehension here. Since python 3, list
  557. # comprehensions use a generator internally. This means you can't yield
  558. # inside of a list comprehension anymore.
  559. interested_list = []
  560. for s in services:
  561. if await s.is_interested(event, self.store):
  562. interested_list.append(s)
  563. return interested_list
  564. def _get_services_for_user(self, user_id: str) -> List[ApplicationService]:
  565. services = self.store.get_app_services()
  566. return [s for s in services if (s.is_interested_in_user(user_id))]
  567. def _get_services_for_3pn(self, protocol: str) -> List[ApplicationService]:
  568. services = self.store.get_app_services()
  569. return [s for s in services if s.is_interested_in_protocol(protocol)]
  570. async def _is_unknown_user(self, user_id: str) -> bool:
  571. if not self.is_mine_id(user_id):
  572. # we don't know if they are unknown or not since it isn't one of our
  573. # users. We can't poke ASes.
  574. return False
  575. user_info = await self.store.get_user_by_id(user_id)
  576. if user_info:
  577. return False
  578. # user not found; could be the AS though, so check.
  579. services = self.store.get_app_services()
  580. service_list = [s for s in services if s.sender == user_id]
  581. return len(service_list) == 0
  582. async def _check_user_exists(self, user_id: str) -> bool:
  583. unknown_user = await self._is_unknown_user(user_id)
  584. if unknown_user:
  585. return await self.query_user_exists(user_id)
  586. return True