appservice.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015, 2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from typing import TYPE_CHECKING, Dict, List, Optional, Union
  17. from prometheus_client import Counter
  18. from twisted.internet import defer
  19. import synapse
  20. from synapse.api.constants import EventTypes
  21. from synapse.appservice import ApplicationService
  22. from synapse.events import EventBase
  23. from synapse.handlers.presence import format_user_presence_state
  24. from synapse.logging.context import make_deferred_yieldable, run_in_background
  25. from synapse.metrics import (
  26. event_processing_loop_counter,
  27. event_processing_loop_room_count,
  28. )
  29. from synapse.metrics.background_process_metrics import (
  30. run_as_background_process,
  31. wrap_as_background_process,
  32. )
  33. from synapse.storage.databases.main.directory import RoomAliasMapping
  34. from synapse.types import Collection, JsonDict, RoomAlias, RoomStreamToken, UserID
  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_datastore()
  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.notify_appservices
  49. self.event_sources = hs.get_event_sources()
  50. self.current_max = 0
  51. self.is_processing = False
  52. def notify_interested_services(self, max_token: RoomStreamToken):
  53. """Notifies (pushes) all application services interested in this event.
  54. Pushing is done asynchronously, so this method won't block for any
  55. prolonged length of time.
  56. """
  57. # We just use the minimum stream ordering and ignore the vector clock
  58. # component. This is safe to do as long as we *always* ignore the vector
  59. # clock components.
  60. current_id = max_token.stream
  61. services = self.store.get_app_services()
  62. if not services or not self.notify_appservices:
  63. return
  64. self.current_max = max(self.current_max, current_id)
  65. if self.is_processing:
  66. return
  67. # We only start a new background process if necessary rather than
  68. # optimistically (to cut down on overhead).
  69. self._notify_interested_services(max_token)
  70. @wrap_as_background_process("notify_interested_services")
  71. async def _notify_interested_services(self, max_token: RoomStreamToken):
  72. with Measure(self.clock, "notify_interested_services"):
  73. self.is_processing = True
  74. try:
  75. limit = 100
  76. while True:
  77. (
  78. upper_bound,
  79. events,
  80. ) = await self.store.get_new_events_for_appservice(
  81. self.current_max, limit
  82. )
  83. if not events:
  84. break
  85. events_by_room = {} # type: Dict[str, List[EventBase]]
  86. for event in events:
  87. events_by_room.setdefault(event.room_id, []).append(event)
  88. async def handle_event(event):
  89. # Gather interested services
  90. services = await self._get_services_for_event(event)
  91. if len(services) == 0:
  92. return # no services need notifying
  93. # Do we know this user exists? If not, poke the user
  94. # query API for all services which match that user regex.
  95. # This needs to block as these user queries need to be
  96. # made BEFORE pushing the event.
  97. await self._check_user_exists(event.sender)
  98. if event.type == EventTypes.Member:
  99. await self._check_user_exists(event.state_key)
  100. if not self.started_scheduler:
  101. async def start_scheduler():
  102. try:
  103. return await self.scheduler.start()
  104. except Exception:
  105. logger.error("Application Services Failure")
  106. run_as_background_process("as_scheduler", start_scheduler)
  107. self.started_scheduler = True
  108. # Fork off pushes to these services
  109. for service in services:
  110. self.scheduler.submit_event_for_as(service, event)
  111. now = self.clock.time_msec()
  112. ts = await self.store.get_received_ts(event.event_id)
  113. synapse.metrics.event_processing_lag_by_event.labels(
  114. "appservice_sender"
  115. ).observe((now - ts) / 1000)
  116. async def handle_room_events(events):
  117. for event in events:
  118. await handle_event(event)
  119. await make_deferred_yieldable(
  120. defer.gatherResults(
  121. [
  122. run_in_background(handle_room_events, evs)
  123. for evs in events_by_room.values()
  124. ],
  125. consumeErrors=True,
  126. )
  127. )
  128. await self.store.set_appservice_last_pos(upper_bound)
  129. now = self.clock.time_msec()
  130. ts = await self.store.get_received_ts(events[-1].event_id)
  131. synapse.metrics.event_processing_positions.labels(
  132. "appservice_sender"
  133. ).set(upper_bound)
  134. events_processed_counter.inc(len(events))
  135. event_processing_loop_room_count.labels("appservice_sender").inc(
  136. len(events_by_room)
  137. )
  138. event_processing_loop_counter.labels("appservice_sender").inc()
  139. synapse.metrics.event_processing_lag.labels(
  140. "appservice_sender"
  141. ).set(now - ts)
  142. synapse.metrics.event_processing_last_ts.labels(
  143. "appservice_sender"
  144. ).set(ts)
  145. finally:
  146. self.is_processing = False
  147. def notify_interested_services_ephemeral(
  148. self,
  149. stream_key: str,
  150. new_token: Optional[int],
  151. users: Collection[Union[str, UserID]] = [],
  152. ):
  153. """This is called by the notifier in the background
  154. when a ephemeral event handled by the homeserver.
  155. This will determine which appservices
  156. are interested in the event, and submit them.
  157. Events will only be pushed to appservices
  158. that have opted into ephemeral events
  159. Args:
  160. stream_key: The stream the event came from.
  161. new_token: The latest stream token
  162. users: The user(s) involved with the event.
  163. """
  164. if not self.notify_appservices:
  165. return
  166. if stream_key not in ("typing_key", "receipt_key", "presence_key"):
  167. return
  168. services = [
  169. service
  170. for service in self.store.get_app_services()
  171. if service.supports_ephemeral
  172. ]
  173. if not services:
  174. return
  175. # We only start a new background process if necessary rather than
  176. # optimistically (to cut down on overhead).
  177. self._notify_interested_services_ephemeral(
  178. services, stream_key, new_token, users
  179. )
  180. @wrap_as_background_process("notify_interested_services_ephemeral")
  181. async def _notify_interested_services_ephemeral(
  182. self,
  183. services: List[ApplicationService],
  184. stream_key: str,
  185. new_token: Optional[int],
  186. users: Collection[Union[str, UserID]],
  187. ):
  188. logger.debug("Checking interested services for %s" % (stream_key))
  189. with Measure(self.clock, "notify_interested_services_ephemeral"):
  190. for service in services:
  191. # Only handle typing if we have the latest token
  192. if stream_key == "typing_key" and new_token is not None:
  193. events = await self._handle_typing(service, new_token)
  194. if events:
  195. self.scheduler.submit_ephemeral_events_for_as(service, events)
  196. # We don't persist the token for typing_key for performance reasons
  197. elif stream_key == "receipt_key":
  198. events = await self._handle_receipts(service)
  199. if events:
  200. self.scheduler.submit_ephemeral_events_for_as(service, events)
  201. await self.store.set_type_stream_id_for_appservice(
  202. service, "read_receipt", new_token
  203. )
  204. elif stream_key == "presence_key":
  205. events = await self._handle_presence(service, users)
  206. if events:
  207. self.scheduler.submit_ephemeral_events_for_as(service, events)
  208. await self.store.set_type_stream_id_for_appservice(
  209. service, "presence", new_token
  210. )
  211. async def _handle_typing(
  212. self, service: ApplicationService, new_token: int
  213. ) -> List[JsonDict]:
  214. typing_source = self.event_sources.sources["typing"]
  215. # Get the typing events from just before current
  216. typing, _ = await typing_source.get_new_events_as(
  217. service=service,
  218. # For performance reasons, we don't persist the previous
  219. # token in the DB and instead fetch the latest typing information
  220. # for appservices.
  221. from_key=new_token - 1,
  222. )
  223. return typing
  224. async def _handle_receipts(self, service: ApplicationService) -> List[JsonDict]:
  225. from_key = await self.store.get_type_stream_id_for_appservice(
  226. service, "read_receipt"
  227. )
  228. receipts_source = self.event_sources.sources["receipt"]
  229. receipts, _ = await receipts_source.get_new_events_as(
  230. service=service, from_key=from_key
  231. )
  232. return receipts
  233. async def _handle_presence(
  234. self, service: ApplicationService, users: Collection[Union[str, UserID]]
  235. ) -> List[JsonDict]:
  236. events = [] # type: List[JsonDict]
  237. presence_source = self.event_sources.sources["presence"]
  238. from_key = await self.store.get_type_stream_id_for_appservice(
  239. service, "presence"
  240. )
  241. for user in users:
  242. if isinstance(user, str):
  243. user = UserID.from_string(user)
  244. interested = await service.is_interested_in_presence(user, self.store)
  245. if not interested:
  246. continue
  247. presence_events, _ = await presence_source.get_new_events(
  248. user=user,
  249. service=service,
  250. from_key=from_key,
  251. )
  252. time_now = self.clock.time_msec()
  253. events.extend(
  254. {
  255. "type": "m.presence",
  256. "sender": event.user_id,
  257. "content": format_user_presence_state(
  258. event, time_now, include_user_id=False
  259. ),
  260. }
  261. for event in presence_events
  262. )
  263. return events
  264. async def query_user_exists(self, user_id: str) -> bool:
  265. """Check if any application service knows this user_id exists.
  266. Args:
  267. user_id: The user to query if they exist on any AS.
  268. Returns:
  269. True if this user exists on at least one application service.
  270. """
  271. user_query_services = self._get_services_for_user(user_id=user_id)
  272. for user_service in user_query_services:
  273. is_known_user = await self.appservice_api.query_user(user_service, user_id)
  274. if is_known_user:
  275. return True
  276. return False
  277. async def query_room_alias_exists(
  278. self, room_alias: RoomAlias
  279. ) -> Optional[RoomAliasMapping]:
  280. """Check if an application service knows this room alias exists.
  281. Args:
  282. room_alias: The room alias to query.
  283. Returns:
  284. namedtuple: with keys "room_id" and "servers" or None if no
  285. association can be found.
  286. """
  287. room_alias_str = room_alias.to_string()
  288. services = self.store.get_app_services()
  289. alias_query_services = [
  290. s for s in services if (s.is_interested_in_alias(room_alias_str))
  291. ]
  292. for alias_service in alias_query_services:
  293. is_known_alias = await self.appservice_api.query_alias(
  294. alias_service, room_alias_str
  295. )
  296. if is_known_alias:
  297. # the alias exists now so don't query more ASes.
  298. return await self.store.get_association_from_room_alias(room_alias)
  299. return None
  300. async def query_3pe(
  301. self, kind: str, protocol: str, fields: Dict[bytes, List[bytes]]
  302. ) -> List[JsonDict]:
  303. services = self._get_services_for_3pn(protocol)
  304. results = await make_deferred_yieldable(
  305. defer.DeferredList(
  306. [
  307. run_in_background(
  308. self.appservice_api.query_3pe, service, kind, protocol, fields
  309. )
  310. for service in services
  311. ],
  312. consumeErrors=True,
  313. )
  314. )
  315. ret = []
  316. for (success, result) in results:
  317. if success:
  318. ret.extend(result)
  319. return ret
  320. async def get_3pe_protocols(
  321. self, only_protocol: Optional[str] = None
  322. ) -> Dict[str, JsonDict]:
  323. services = self.store.get_app_services()
  324. protocols = {} # type: Dict[str, List[JsonDict]]
  325. # Collect up all the individual protocol responses out of the ASes
  326. for s in services:
  327. for p in s.protocols:
  328. if only_protocol is not None and p != only_protocol:
  329. continue
  330. if p not in protocols:
  331. protocols[p] = []
  332. info = await self.appservice_api.get_3pe_protocol(s, p)
  333. if info is not None:
  334. protocols[p].append(info)
  335. def _merge_instances(infos: List[JsonDict]) -> JsonDict:
  336. if not infos:
  337. return {}
  338. # Merge the 'instances' lists of multiple results, but just take
  339. # the other fields from the first as they ought to be identical
  340. # copy the result so as not to corrupt the cached one
  341. combined = dict(infos[0])
  342. combined["instances"] = list(combined["instances"])
  343. for info in infos[1:]:
  344. combined["instances"].extend(info["instances"])
  345. return combined
  346. return {p: _merge_instances(protocols[p]) for p in protocols.keys()}
  347. async def _get_services_for_event(
  348. self, event: EventBase
  349. ) -> List[ApplicationService]:
  350. """Retrieve a list of application services interested in this event.
  351. Args:
  352. event: The event to check. Can be None if alias_list is not.
  353. Returns:
  354. A list of services interested in this event based on the service regex.
  355. """
  356. services = self.store.get_app_services()
  357. # we can't use a list comprehension here. Since python 3, list
  358. # comprehensions use a generator internally. This means you can't yield
  359. # inside of a list comprehension anymore.
  360. interested_list = []
  361. for s in services:
  362. if await s.is_interested(event, self.store):
  363. interested_list.append(s)
  364. return interested_list
  365. def _get_services_for_user(self, user_id: str) -> List[ApplicationService]:
  366. services = self.store.get_app_services()
  367. return [s for s in services if (s.is_interested_in_user(user_id))]
  368. def _get_services_for_3pn(self, protocol: str) -> List[ApplicationService]:
  369. services = self.store.get_app_services()
  370. return [s for s in services if s.is_interested_in_protocol(protocol)]
  371. async def _is_unknown_user(self, user_id: str) -> bool:
  372. if not self.is_mine_id(user_id):
  373. # we don't know if they are unknown or not since it isn't one of our
  374. # users. We can't poke ASes.
  375. return False
  376. user_info = await self.store.get_user_by_id(user_id)
  377. if user_info:
  378. return False
  379. # user not found; could be the AS though, so check.
  380. services = self.store.get_app_services()
  381. service_list = [s for s in services if s.sender == user_id]
  382. return len(service_list) == 0
  383. async def _check_user_exists(self, user_id: str) -> bool:
  384. unknown_user = await self._is_unknown_user(user_id)
  385. if unknown_user:
  386. return await self.query_user_exists(user_id)
  387. return True