Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

965 wiersze
38 KiB

  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 (
  16. TYPE_CHECKING,
  17. Collection,
  18. Dict,
  19. Iterable,
  20. List,
  21. Mapping,
  22. Optional,
  23. Tuple,
  24. Union,
  25. )
  26. from prometheus_client import Counter
  27. from twisted.internet import defer
  28. import synapse
  29. from synapse.api.constants import EduTypes, EventTypes
  30. from synapse.appservice import ApplicationService
  31. from synapse.events import EventBase
  32. from synapse.handlers.presence import format_user_presence_state
  33. from synapse.logging.context import make_deferred_yieldable, run_in_background
  34. from synapse.metrics import (
  35. event_processing_loop_counter,
  36. event_processing_loop_room_count,
  37. )
  38. from synapse.metrics.background_process_metrics import (
  39. run_as_background_process,
  40. wrap_as_background_process,
  41. )
  42. from synapse.storage.databases.main.directory import RoomAliasMapping
  43. from synapse.types import (
  44. DeviceListUpdates,
  45. JsonDict,
  46. JsonMapping,
  47. RoomAlias,
  48. RoomStreamToken,
  49. StreamKeyType,
  50. UserID,
  51. )
  52. from synapse.util.async_helpers import Linearizer
  53. from synapse.util.metrics import Measure
  54. if TYPE_CHECKING:
  55. from synapse.server import HomeServer
  56. logger = logging.getLogger(__name__)
  57. events_processed_counter = Counter("synapse_handlers_appservice_events_processed", "")
  58. class ApplicationServicesHandler:
  59. def __init__(self, hs: "HomeServer"):
  60. self.store = hs.get_datastores().main
  61. self.is_mine_id = hs.is_mine_id
  62. self.appservice_api = hs.get_application_service_api()
  63. self.scheduler = hs.get_application_service_scheduler()
  64. self.started_scheduler = False
  65. self.clock = hs.get_clock()
  66. self.notify_appservices = hs.config.worker.should_notify_appservices
  67. self.event_sources = hs.get_event_sources()
  68. self._msc2409_to_device_messages_enabled = (
  69. hs.config.experimental.msc2409_to_device_messages_enabled
  70. )
  71. self._msc3202_transaction_extensions_enabled = (
  72. hs.config.experimental.msc3202_transaction_extensions
  73. )
  74. self.current_max = 0
  75. self.is_processing = False
  76. self._ephemeral_events_linearizer = Linearizer(
  77. name="appservice_ephemeral_events"
  78. )
  79. def notify_interested_services(self, max_token: RoomStreamToken) -> None:
  80. """Notifies (pushes) all application services interested in this event.
  81. Pushing is done asynchronously, so this method won't block for any
  82. prolonged length of time.
  83. """
  84. # We just use the minimum stream ordering and ignore the vector clock
  85. # component. This is safe to do as long as we *always* ignore the vector
  86. # clock components.
  87. current_id = max_token.stream
  88. services = self.store.get_app_services()
  89. if not services or not self.notify_appservices:
  90. return
  91. self.current_max = max(self.current_max, current_id)
  92. if self.is_processing:
  93. return
  94. # We only start a new background process if necessary rather than
  95. # optimistically (to cut down on overhead).
  96. self._notify_interested_services(max_token)
  97. @wrap_as_background_process("notify_interested_services")
  98. async def _notify_interested_services(self, max_token: RoomStreamToken) -> None:
  99. with Measure(self.clock, "notify_interested_services"):
  100. self.is_processing = True
  101. try:
  102. upper_bound = -1
  103. while upper_bound < self.current_max:
  104. last_token = await self.store.get_appservice_last_pos()
  105. (
  106. upper_bound,
  107. event_to_received_ts,
  108. ) = await self.store.get_all_new_event_ids_stream(
  109. last_token, self.current_max, limit=100
  110. )
  111. events = await self.store.get_events_as_list(
  112. event_to_received_ts.keys(), get_prev_content=True
  113. )
  114. events_by_room: Dict[str, List[EventBase]] = {}
  115. for event in events:
  116. events_by_room.setdefault(event.room_id, []).append(event)
  117. async def handle_event(event: EventBase) -> None:
  118. # Gather interested services
  119. services = await self._get_services_for_event(event)
  120. if len(services) == 0:
  121. return # no services need notifying
  122. # Do we know this user exists? If not, poke the user
  123. # query API for all services which match that user regex.
  124. # This needs to block as these user queries need to be
  125. # made BEFORE pushing the event.
  126. await self._check_user_exists(event.sender)
  127. if event.type == EventTypes.Member:
  128. await self._check_user_exists(event.state_key)
  129. if not self.started_scheduler:
  130. async def start_scheduler() -> None:
  131. try:
  132. await self.scheduler.start()
  133. except Exception:
  134. logger.error("Application Services Failure")
  135. run_as_background_process("as_scheduler", start_scheduler)
  136. self.started_scheduler = True
  137. # Fork off pushes to these services
  138. for service in services:
  139. self.scheduler.enqueue_for_appservice(
  140. service, events=[event]
  141. )
  142. now = self.clock.time_msec()
  143. ts = event_to_received_ts[event.event_id]
  144. assert ts is not None
  145. synapse.metrics.event_processing_lag_by_event.labels(
  146. "appservice_sender"
  147. ).observe((now - ts) / 1000)
  148. async def handle_room_events(events: Iterable[EventBase]) -> None:
  149. for event in events:
  150. await handle_event(event)
  151. await make_deferred_yieldable(
  152. defer.gatherResults(
  153. [
  154. run_in_background(handle_room_events, evs)
  155. for evs in events_by_room.values()
  156. ],
  157. consumeErrors=True,
  158. )
  159. )
  160. await self.store.set_appservice_last_pos(upper_bound)
  161. synapse.metrics.event_processing_positions.labels(
  162. "appservice_sender"
  163. ).set(upper_bound)
  164. events_processed_counter.inc(len(events))
  165. event_processing_loop_room_count.labels("appservice_sender").inc(
  166. len(events_by_room)
  167. )
  168. event_processing_loop_counter.labels("appservice_sender").inc()
  169. if events:
  170. now = self.clock.time_msec()
  171. ts = event_to_received_ts[events[-1].event_id]
  172. assert ts is not None
  173. synapse.metrics.event_processing_lag.labels(
  174. "appservice_sender"
  175. ).set(now - ts)
  176. synapse.metrics.event_processing_last_ts.labels(
  177. "appservice_sender"
  178. ).set(ts)
  179. finally:
  180. self.is_processing = False
  181. def notify_interested_services_ephemeral(
  182. self,
  183. stream_key: str,
  184. new_token: Union[int, RoomStreamToken],
  185. users: Collection[Union[str, UserID]],
  186. ) -> None:
  187. """
  188. This is called by the notifier in the background when an ephemeral event is handled
  189. by the homeserver.
  190. This will determine which appservices are interested in the event, and submit them.
  191. Args:
  192. stream_key: The stream the event came from.
  193. `stream_key` can be StreamKeyType.TYPING, StreamKeyType.RECEIPT, StreamKeyType.PRESENCE,
  194. StreamKeyType.TO_DEVICE or StreamKeyType.DEVICE_LIST. Any other value for `stream_key`
  195. will cause this function to return early.
  196. Ephemeral events will only be pushed to appservices that have opted into
  197. receiving them by setting `push_ephemeral` to true in their registration
  198. file. Note that while MSC2409 is experimental, this option is called
  199. `de.sorunome.msc2409.push_ephemeral`.
  200. Appservices will only receive ephemeral events that fall within their
  201. registered user and room namespaces.
  202. new_token: The stream token of the event.
  203. users: The users that should be informed of the new event, if any.
  204. """
  205. if not self.notify_appservices:
  206. return
  207. # Notify appservices of updates in ephemeral event streams.
  208. # Only the following streams are currently supported.
  209. # FIXME: We should use constants for these values.
  210. if stream_key not in (
  211. StreamKeyType.TYPING,
  212. StreamKeyType.RECEIPT,
  213. StreamKeyType.PRESENCE,
  214. StreamKeyType.TO_DEVICE,
  215. StreamKeyType.DEVICE_LIST,
  216. ):
  217. return
  218. # Assert that new_token is an integer (and not a RoomStreamToken).
  219. # All of the supported streams that this function handles use an
  220. # integer to track progress (rather than a RoomStreamToken - a
  221. # vector clock implementation) as they don't support multiple
  222. # stream writers.
  223. #
  224. # As a result, we simply assert that new_token is an integer.
  225. # If we do end up needing to pass a RoomStreamToken down here
  226. # in the future, using RoomStreamToken.stream (the minimum stream
  227. # position) to convert to an ascending integer value should work.
  228. # Additional context: https://github.com/matrix-org/synapse/pull/11137
  229. assert isinstance(new_token, int)
  230. # Ignore to-device messages if the feature flag is not enabled
  231. if (
  232. stream_key == StreamKeyType.TO_DEVICE
  233. and not self._msc2409_to_device_messages_enabled
  234. ):
  235. return
  236. # Ignore device lists if the feature flag is not enabled
  237. if (
  238. stream_key == StreamKeyType.DEVICE_LIST
  239. and not self._msc3202_transaction_extensions_enabled
  240. ):
  241. return
  242. # Check whether there are any appservices which have registered to receive
  243. # ephemeral events.
  244. #
  245. # Note that whether these events are actually relevant to these appservices
  246. # is decided later on.
  247. services = self.store.get_app_services()
  248. services = [
  249. service
  250. for service in services
  251. # Different stream keys require different support booleans
  252. if (
  253. stream_key
  254. in (
  255. StreamKeyType.TYPING,
  256. StreamKeyType.RECEIPT,
  257. StreamKeyType.PRESENCE,
  258. StreamKeyType.TO_DEVICE,
  259. )
  260. and service.supports_ephemeral
  261. )
  262. or (
  263. stream_key == StreamKeyType.DEVICE_LIST
  264. and service.msc3202_transaction_extensions
  265. )
  266. ]
  267. if not services:
  268. # Bail out early if none of the target appservices have explicitly registered
  269. # to receive these ephemeral events.
  270. return
  271. # We only start a new background process if necessary rather than
  272. # optimistically (to cut down on overhead).
  273. self._notify_interested_services_ephemeral(
  274. services, stream_key, new_token, users
  275. )
  276. @wrap_as_background_process("notify_interested_services_ephemeral")
  277. async def _notify_interested_services_ephemeral(
  278. self,
  279. services: List[ApplicationService],
  280. stream_key: str,
  281. new_token: int,
  282. users: Collection[Union[str, UserID]],
  283. ) -> None:
  284. logger.debug("Checking interested services for %s", stream_key)
  285. with Measure(self.clock, "notify_interested_services_ephemeral"):
  286. for service in services:
  287. if stream_key == StreamKeyType.TYPING:
  288. # Note that we don't persist the token (via set_appservice_stream_type_pos)
  289. # for typing_key due to performance reasons and due to their highly
  290. # ephemeral nature.
  291. #
  292. # Instead we simply grab the latest typing updates in _handle_typing
  293. # and, if they apply to this application service, send it off.
  294. events = await self._handle_typing(service, new_token)
  295. if events:
  296. self.scheduler.enqueue_for_appservice(service, ephemeral=events)
  297. continue
  298. # Since we read/update the stream position for this AS/stream
  299. async with self._ephemeral_events_linearizer.queue(
  300. (service.id, stream_key)
  301. ):
  302. if stream_key == StreamKeyType.RECEIPT:
  303. events = await self._handle_receipts(service, new_token)
  304. self.scheduler.enqueue_for_appservice(service, ephemeral=events)
  305. # Persist the latest handled stream token for this appservice
  306. await self.store.set_appservice_stream_type_pos(
  307. service, "read_receipt", new_token
  308. )
  309. elif stream_key == StreamKeyType.PRESENCE:
  310. events = await self._handle_presence(service, users, new_token)
  311. self.scheduler.enqueue_for_appservice(service, ephemeral=events)
  312. # Persist the latest handled stream token for this appservice
  313. await self.store.set_appservice_stream_type_pos(
  314. service, "presence", new_token
  315. )
  316. elif stream_key == StreamKeyType.TO_DEVICE:
  317. # Retrieve a list of to-device message events, as well as the
  318. # maximum stream token of the messages we were able to retrieve.
  319. to_device_messages = await self._get_to_device_messages(
  320. service, new_token, users
  321. )
  322. self.scheduler.enqueue_for_appservice(
  323. service, to_device_messages=to_device_messages
  324. )
  325. # Persist the latest handled stream token for this appservice
  326. await self.store.set_appservice_stream_type_pos(
  327. service, "to_device", new_token
  328. )
  329. elif stream_key == StreamKeyType.DEVICE_LIST:
  330. device_list_summary = await self._get_device_list_summary(
  331. service, new_token
  332. )
  333. if device_list_summary:
  334. self.scheduler.enqueue_for_appservice(
  335. service, device_list_summary=device_list_summary
  336. )
  337. # Persist the latest handled stream token for this appservice
  338. await self.store.set_appservice_stream_type_pos(
  339. service, "device_list", new_token
  340. )
  341. async def _handle_typing(
  342. self, service: ApplicationService, new_token: int
  343. ) -> List[JsonMapping]:
  344. """
  345. Return the typing events since the given stream token that the given application
  346. service should receive.
  347. First fetch all typing events between the given typing stream token (non-inclusive)
  348. and the latest typing event stream token (inclusive). Then return only those typing
  349. events that the given application service may be interested in.
  350. Args:
  351. service: The application service to check for which events it should receive.
  352. new_token: A typing event stream token.
  353. Returns:
  354. A list of JSON dictionaries containing data derived from the typing events that
  355. should be sent to the given application service.
  356. """
  357. typing_source = self.event_sources.sources.typing
  358. # Get the typing events from just before current
  359. typing, _ = await typing_source.get_new_events_as(
  360. service=service,
  361. # For performance reasons, we don't persist the previous
  362. # token in the DB and instead fetch the latest typing event
  363. # for appservices.
  364. # TODO: It'd likely be more efficient to simply fetch the
  365. # typing event with the given 'new_token' stream token and
  366. # check if the given service was interested, rather than
  367. # iterating over all typing events and only grabbing the
  368. # latest few.
  369. from_key=new_token - 1,
  370. )
  371. return typing
  372. async def _handle_receipts(
  373. self, service: ApplicationService, new_token: int
  374. ) -> List[JsonMapping]:
  375. """
  376. Return the latest read receipts that the given application service should receive.
  377. First fetch all read receipts between the last receipt stream token that this
  378. application service should have previously received (non-inclusive) and the
  379. latest read receipt stream token (inclusive). Then from that set, return only
  380. those read receipts that the given application service may be interested in.
  381. Args:
  382. service: The application service to check for which events it should receive.
  383. new_token: A receipts event stream token. Purely used to double-check that the
  384. from_token we pull from the database isn't greater than or equal to this
  385. token. Prevents accidentally duplicating work.
  386. Returns:
  387. A list of JSON dictionaries containing data derived from the read receipts that
  388. should be sent to the given application service.
  389. """
  390. from_key = await self.store.get_type_stream_id_for_appservice(
  391. service, "read_receipt"
  392. )
  393. if new_token is not None and new_token <= from_key:
  394. logger.debug(
  395. "Rejecting token lower than or equal to stored: %s" % (new_token,)
  396. )
  397. return []
  398. receipts_source = self.event_sources.sources.receipt
  399. receipts, _ = await receipts_source.get_new_events_as(
  400. service=service, from_key=from_key, to_key=new_token
  401. )
  402. return receipts
  403. async def _handle_presence(
  404. self,
  405. service: ApplicationService,
  406. users: Collection[Union[str, UserID]],
  407. new_token: Optional[int],
  408. ) -> List[JsonMapping]:
  409. """
  410. Return the latest presence updates that the given application service should receive.
  411. First, filter the given users list to those that the application service is
  412. interested in. Then retrieve the latest presence updates since the
  413. the last-known previously received presence stream token for the given
  414. application service. Return those presence updates.
  415. Args:
  416. service: The application service that ephemeral events are being sent to.
  417. users: The users that should receive the presence update.
  418. new_token: A presence update stream token. Purely used to double-check that the
  419. from_token we pull from the database isn't greater than or equal to this
  420. token. Prevents accidentally duplicating work.
  421. Returns:
  422. A list of json dictionaries containing data derived from the presence events
  423. that should be sent to the given application service.
  424. """
  425. events: List[JsonMapping] = []
  426. presence_source = self.event_sources.sources.presence
  427. from_key = await self.store.get_type_stream_id_for_appservice(
  428. service, "presence"
  429. )
  430. if new_token is not None and new_token <= from_key:
  431. logger.debug(
  432. "Rejecting token lower than or equal to stored: %s" % (new_token,)
  433. )
  434. return []
  435. for user in users:
  436. if isinstance(user, str):
  437. user = UserID.from_string(user)
  438. interested = await service.is_interested_in_presence(user, self.store)
  439. if not interested:
  440. continue
  441. presence_events, _ = await presence_source.get_new_events(
  442. user=user,
  443. from_key=from_key,
  444. )
  445. time_now = self.clock.time_msec()
  446. events.extend(
  447. {
  448. "type": EduTypes.PRESENCE,
  449. "sender": event.user_id,
  450. "content": format_user_presence_state(
  451. event, time_now, include_user_id=False
  452. ),
  453. }
  454. for event in presence_events
  455. )
  456. return events
  457. async def _get_to_device_messages(
  458. self,
  459. service: ApplicationService,
  460. new_token: int,
  461. users: Collection[Union[str, UserID]],
  462. ) -> List[JsonDict]:
  463. """
  464. Given an application service, determine which events it should receive
  465. from those between the last-recorded to-device message stream token for this
  466. appservice and the given stream token.
  467. Args:
  468. service: The application service to check for which events it should receive.
  469. new_token: The latest to-device event stream token.
  470. users: The users to be notified for the new to-device messages
  471. (ie, the recipients of the messages).
  472. Returns:
  473. A list of JSON dictionaries containing data derived from the to-device events
  474. that should be sent to the given application service.
  475. """
  476. # Get the stream token that this application service has processed up until
  477. from_key = await self.store.get_type_stream_id_for_appservice(
  478. service, "to_device"
  479. )
  480. # Filter out users that this appservice is not interested in
  481. users_appservice_is_interested_in: List[str] = []
  482. for user in users:
  483. # FIXME: We should do this farther up the call stack. We currently repeat
  484. # this operation in _handle_presence.
  485. if isinstance(user, UserID):
  486. user = user.to_string()
  487. if service.is_interested_in_user(user):
  488. users_appservice_is_interested_in.append(user)
  489. if not users_appservice_is_interested_in:
  490. # Return early if the AS was not interested in any of these users
  491. return []
  492. # Retrieve the to-device messages for each user
  493. recipient_device_to_messages = await self.store.get_messages_for_user_devices(
  494. users_appservice_is_interested_in,
  495. from_key,
  496. new_token,
  497. )
  498. # According to MSC2409, we'll need to add 'to_user_id' and 'to_device_id' fields
  499. # to the event JSON so that the application service will know which user/device
  500. # combination this messages was intended for.
  501. #
  502. # So we mangle this dict into a flat list of to-device messages with the relevant
  503. # user ID and device ID embedded inside each message dict.
  504. message_payload: List[JsonDict] = []
  505. for (
  506. user_id,
  507. device_id,
  508. ), messages in recipient_device_to_messages.items():
  509. for message_json in messages:
  510. message_payload.append(
  511. {
  512. "to_user_id": user_id,
  513. "to_device_id": device_id,
  514. **message_json,
  515. }
  516. )
  517. return message_payload
  518. async def _get_device_list_summary(
  519. self,
  520. appservice: ApplicationService,
  521. new_key: int,
  522. ) -> DeviceListUpdates:
  523. """
  524. Retrieve a list of users who have changed their device lists.
  525. Args:
  526. appservice: The application service to retrieve device list changes for.
  527. new_key: The stream key of the device list change that triggered this method call.
  528. Returns:
  529. A set of device list updates, comprised of users that the appservices needs to:
  530. * resync the device list of, and
  531. * stop tracking the device list of.
  532. """
  533. # Fetch the last successfully processed device list update stream ID
  534. # for this appservice.
  535. from_key = await self.store.get_type_stream_id_for_appservice(
  536. appservice, "device_list"
  537. )
  538. # Fetch the users who have modified their device list since then.
  539. users_with_changed_device_lists = await self.store.get_all_devices_changed(
  540. from_key, to_key=new_key
  541. )
  542. # Filter out any users the application service is not interested in
  543. #
  544. # For each user who changed their device list, we want to check whether this
  545. # appservice would be interested in the change.
  546. filtered_users_with_changed_device_lists = {
  547. user_id
  548. for user_id in users_with_changed_device_lists
  549. if await self._is_appservice_interested_in_device_lists_of_user(
  550. appservice, user_id
  551. )
  552. }
  553. # Create a summary of "changed" and "left" users.
  554. # TODO: Calculate "left" users.
  555. device_list_summary = DeviceListUpdates(
  556. changed=filtered_users_with_changed_device_lists
  557. )
  558. return device_list_summary
  559. async def _is_appservice_interested_in_device_lists_of_user(
  560. self,
  561. appservice: ApplicationService,
  562. user_id: str,
  563. ) -> bool:
  564. """
  565. Returns whether a given application service is interested in the device list
  566. updates of a given user.
  567. The application service is interested in the user's device list updates if any
  568. of the following are true:
  569. * The user is the appservice's sender localpart user.
  570. * The user is in the appservice's user namespace.
  571. * At least one member of one room that the user is a part of is in the
  572. appservice's user namespace.
  573. * The appservice is explicitly (via room ID or alias) interested in at
  574. least one room that the user is in.
  575. Args:
  576. appservice: The application service to gauge interest of.
  577. user_id: The ID of the user whose device list interest is in question.
  578. Returns:
  579. True if the application service is interested in the user's device lists, False
  580. otherwise.
  581. """
  582. # This method checks against both the sender localpart user as well as if the
  583. # user is in the appservice's user namespace.
  584. if appservice.is_interested_in_user(user_id):
  585. return True
  586. # Determine whether any of the rooms the user is in justifies sending this
  587. # device list update to the application service.
  588. room_ids = await self.store.get_rooms_for_user(user_id)
  589. for room_id in room_ids:
  590. # This method covers checking room members for appservice interest as well as
  591. # room ID and alias checks.
  592. if await appservice.is_interested_in_room(room_id, self.store):
  593. return True
  594. return False
  595. async def query_user_exists(self, user_id: str) -> bool:
  596. """Check if any application service knows this user_id exists.
  597. Args:
  598. user_id: The user to query if they exist on any AS.
  599. Returns:
  600. True if this user exists on at least one application service.
  601. """
  602. user_query_services = self._get_services_for_user(user_id=user_id)
  603. for user_service in user_query_services:
  604. is_known_user = await self.appservice_api.query_user(user_service, user_id)
  605. if is_known_user:
  606. return True
  607. return False
  608. async def query_room_alias_exists(
  609. self, room_alias: RoomAlias
  610. ) -> Optional[RoomAliasMapping]:
  611. """Check if an application service knows this room alias exists.
  612. Args:
  613. room_alias: The room alias to query.
  614. Returns:
  615. RoomAliasMapping or None if no association can be found.
  616. """
  617. room_alias_str = room_alias.to_string()
  618. services = self.store.get_app_services()
  619. alias_query_services = [
  620. s for s in services if (s.is_room_alias_in_namespace(room_alias_str))
  621. ]
  622. for alias_service in alias_query_services:
  623. is_known_alias = await self.appservice_api.query_alias(
  624. alias_service, room_alias_str
  625. )
  626. if is_known_alias:
  627. # the alias exists now so don't query more ASes.
  628. return await self.store.get_association_from_room_alias(room_alias)
  629. return None
  630. async def query_3pe(
  631. self, kind: str, protocol: str, fields: Dict[bytes, List[bytes]]
  632. ) -> List[JsonDict]:
  633. services = self._get_services_for_3pn(protocol)
  634. results = await make_deferred_yieldable(
  635. defer.DeferredList(
  636. [
  637. run_in_background(
  638. self.appservice_api.query_3pe, service, kind, protocol, fields
  639. )
  640. for service in services
  641. ],
  642. consumeErrors=True,
  643. )
  644. )
  645. ret = []
  646. for success, result in results:
  647. if success:
  648. ret.extend(result)
  649. return ret
  650. async def get_3pe_protocols(
  651. self, only_protocol: Optional[str] = None
  652. ) -> Dict[str, JsonDict]:
  653. services = self.store.get_app_services()
  654. protocols: Dict[str, List[JsonDict]] = {}
  655. # Collect up all the individual protocol responses out of the ASes
  656. for s in services:
  657. for p in s.protocols:
  658. if only_protocol is not None and p != only_protocol:
  659. continue
  660. if p not in protocols:
  661. protocols[p] = []
  662. info = await self.appservice_api.get_3pe_protocol(s, p)
  663. if info is not None:
  664. protocols[p].append(info)
  665. def _merge_instances(infos: List[JsonDict]) -> JsonDict:
  666. # Merge the 'instances' lists of multiple results, but just take
  667. # the other fields from the first as they ought to be identical
  668. # copy the result so as not to corrupt the cached one
  669. combined = dict(infos[0])
  670. combined["instances"] = list(combined["instances"])
  671. for info in infos[1:]:
  672. combined["instances"].extend(info["instances"])
  673. return combined
  674. return {
  675. p: _merge_instances(protocols[p]) for p in protocols.keys() if protocols[p]
  676. }
  677. async def _get_services_for_event(
  678. self, event: EventBase
  679. ) -> List[ApplicationService]:
  680. """Retrieve a list of application services interested in this event.
  681. Args:
  682. event: The event to check.
  683. Returns:
  684. A list of services interested in this event based on the service regex.
  685. """
  686. services = self.store.get_app_services()
  687. # we can't use a list comprehension here. Since python 3, list
  688. # comprehensions use a generator internally. This means you can't yield
  689. # inside of a list comprehension anymore.
  690. interested_list = []
  691. for s in services:
  692. if await s.is_interested_in_event(event.event_id, event, self.store):
  693. interested_list.append(s)
  694. return interested_list
  695. def _get_services_for_user(self, user_id: str) -> List[ApplicationService]:
  696. services = self.store.get_app_services()
  697. return [s for s in services if (s.is_interested_in_user(user_id))]
  698. def _get_services_for_3pn(self, protocol: str) -> List[ApplicationService]:
  699. services = self.store.get_app_services()
  700. return [s for s in services if s.is_interested_in_protocol(protocol)]
  701. async def _is_unknown_user(self, user_id: str) -> bool:
  702. if not self.is_mine_id(user_id):
  703. # we don't know if they are unknown or not since it isn't one of our
  704. # users. We can't poke ASes.
  705. return False
  706. user_info = await self.store.get_user_by_id(user_id)
  707. if user_info:
  708. return False
  709. # user not found; could be the AS though, so check.
  710. services = self.store.get_app_services()
  711. service_list = [s for s in services if s.sender == user_id]
  712. return len(service_list) == 0
  713. async def _check_user_exists(self, user_id: str) -> bool:
  714. unknown_user = await self._is_unknown_user(user_id)
  715. if unknown_user:
  716. return await self.query_user_exists(user_id)
  717. return True
  718. async def claim_e2e_one_time_keys(
  719. self, query: Iterable[Tuple[str, str, str, int]]
  720. ) -> Tuple[
  721. Dict[str, Dict[str, Dict[str, JsonDict]]], List[Tuple[str, str, str, int]]
  722. ]:
  723. """Claim one time keys from application services.
  724. Users which are exclusively owned by an application service are sent a
  725. key claim request to check if the application service provides keys
  726. directly.
  727. Args:
  728. query: An iterable of tuples of (user ID, device ID, algorithm).
  729. Returns:
  730. A tuple of:
  731. A map of user ID -> a map device ID -> a map of key ID -> JSON.
  732. A copy of the input which has not been fulfilled (either because
  733. they are not appservice users or the appservice does not support
  734. providing OTKs).
  735. """
  736. services = self.store.get_app_services()
  737. # Partition the users by appservice.
  738. query_by_appservice: Dict[str, List[Tuple[str, str, str, int]]] = {}
  739. missing = []
  740. for user_id, device, algorithm, count in query:
  741. if not self.store.get_if_app_services_interested_in_user(user_id):
  742. missing.append((user_id, device, algorithm, count))
  743. continue
  744. # Find the associated appservice.
  745. for service in services:
  746. if service.is_exclusive_user(user_id):
  747. query_by_appservice.setdefault(service.id, []).append(
  748. (user_id, device, algorithm, count)
  749. )
  750. continue
  751. # Query each service in parallel.
  752. results = await make_deferred_yieldable(
  753. defer.DeferredList(
  754. [
  755. run_in_background(
  756. self.appservice_api.claim_client_keys,
  757. # We know this must be an app service.
  758. self.store.get_app_service_by_id(service_id), # type: ignore[arg-type]
  759. service_query,
  760. )
  761. for service_id, service_query in query_by_appservice.items()
  762. ],
  763. consumeErrors=True,
  764. )
  765. )
  766. # Patch together the results -- they are all independent (since they
  767. # require exclusive control over the users, which is the outermost key).
  768. claimed_keys: Dict[str, Dict[str, Dict[str, JsonDict]]] = {}
  769. for success, result in results:
  770. if success:
  771. claimed_keys.update(result[0])
  772. missing.extend(result[1])
  773. return claimed_keys, missing
  774. async def query_keys(
  775. self, query: Mapping[str, Optional[List[str]]]
  776. ) -> Dict[str, Dict[str, Dict[str, JsonDict]]]:
  777. """Query application services for device keys.
  778. Users which are exclusively owned by an application service are queried
  779. for keys to check if the application service provides keys directly.
  780. Args:
  781. query: map from user_id to a list of devices to query
  782. Returns:
  783. A map from user_id -> device_id -> device details
  784. """
  785. services = self.store.get_app_services()
  786. # Partition the users by appservice.
  787. query_by_appservice: Dict[str, Dict[str, List[str]]] = {}
  788. for user_id, device_ids in query.items():
  789. if not self.store.get_if_app_services_interested_in_user(user_id):
  790. continue
  791. # Find the associated appservice.
  792. for service in services:
  793. if service.is_exclusive_user(user_id):
  794. query_by_appservice.setdefault(service.id, {})[user_id] = (
  795. device_ids or []
  796. )
  797. continue
  798. # Query each service in parallel.
  799. results = await make_deferred_yieldable(
  800. defer.DeferredList(
  801. [
  802. run_in_background(
  803. self.appservice_api.query_keys,
  804. # We know this must be an app service.
  805. self.store.get_app_service_by_id(service_id), # type: ignore[arg-type]
  806. service_query,
  807. )
  808. for service_id, service_query in query_by_appservice.items()
  809. ],
  810. consumeErrors=True,
  811. )
  812. )
  813. # Patch together the results -- they are all independent (since they
  814. # require exclusive control over the users). They get returned as a single
  815. # dictionary.
  816. key_queries: Dict[str, Dict[str, Dict[str, JsonDict]]] = {}
  817. for success, result in results:
  818. if success:
  819. key_queries.update(result)
  820. return key_queries