appservice.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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 six import itervalues
  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.util.logcontext import make_deferred_yieldable, run_in_background
  22. from synapse.util.metrics import Measure
  23. logger = logging.getLogger(__name__)
  24. events_processed_counter = Counter("synapse_handlers_appservice_events_processed", "")
  25. def log_failure(failure):
  26. logger.error(
  27. "Application Services Failure",
  28. exc_info=(
  29. failure.type,
  30. failure.value,
  31. failure.getTracebackObject()
  32. )
  33. )
  34. class ApplicationServicesHandler(object):
  35. def __init__(self, hs):
  36. self.store = hs.get_datastore()
  37. self.is_mine_id = hs.is_mine_id
  38. self.appservice_api = hs.get_application_service_api()
  39. self.scheduler = hs.get_application_service_scheduler()
  40. self.started_scheduler = False
  41. self.clock = hs.get_clock()
  42. self.notify_appservices = hs.config.notify_appservices
  43. self.current_max = 0
  44. self.is_processing = False
  45. @defer.inlineCallbacks
  46. def notify_interested_services(self, current_id):
  47. """Notifies (pushes) all application services interested in this event.
  48. Pushing is done asynchronously, so this method won't block for any
  49. prolonged length of time.
  50. Args:
  51. current_id(int): The current maximum ID.
  52. """
  53. services = self.store.get_app_services()
  54. if not services or not self.notify_appservices:
  55. return
  56. self.current_max = max(self.current_max, current_id)
  57. if self.is_processing:
  58. return
  59. with Measure(self.clock, "notify_interested_services"):
  60. self.is_processing = True
  61. try:
  62. limit = 100
  63. while True:
  64. upper_bound, events = yield self.store.get_new_events_for_appservice(
  65. self.current_max, limit
  66. )
  67. if not events:
  68. break
  69. events_by_room = {}
  70. for event in events:
  71. events_by_room.setdefault(event.room_id, []).append(event)
  72. @defer.inlineCallbacks
  73. def handle_event(event):
  74. # Gather interested services
  75. services = yield self._get_services_for_event(event)
  76. if len(services) == 0:
  77. return # no services need notifying
  78. # Do we know this user exists? If not, poke the user
  79. # query API for all services which match that user regex.
  80. # This needs to block as these user queries need to be
  81. # made BEFORE pushing the event.
  82. yield self._check_user_exists(event.sender)
  83. if event.type == EventTypes.Member:
  84. yield self._check_user_exists(event.state_key)
  85. if not self.started_scheduler:
  86. self.scheduler.start().addErrback(log_failure)
  87. self.started_scheduler = True
  88. # Fork off pushes to these services
  89. for service in services:
  90. self.scheduler.submit_event_for_as(service, event)
  91. @defer.inlineCallbacks
  92. def handle_room_events(events):
  93. for event in events:
  94. yield handle_event(event)
  95. yield make_deferred_yieldable(defer.gatherResults([
  96. run_in_background(handle_room_events, evs)
  97. for evs in itervalues(events_by_room)
  98. ], consumeErrors=True))
  99. yield self.store.set_appservice_last_pos(upper_bound)
  100. now = self.clock.time_msec()
  101. ts = yield self.store.get_received_ts(events[-1].event_id)
  102. synapse.metrics.event_processing_positions.labels(
  103. "appservice_sender").set(upper_bound)
  104. events_processed_counter.inc(len(events))
  105. synapse.metrics.event_processing_lag.labels(
  106. "appservice_sender").set(now - ts)
  107. synapse.metrics.event_processing_last_ts.labels(
  108. "appservice_sender").set(ts)
  109. finally:
  110. self.is_processing = False
  111. @defer.inlineCallbacks
  112. def query_user_exists(self, user_id):
  113. """Check if any application service knows this user_id exists.
  114. Args:
  115. user_id(str): The user to query if they exist on any AS.
  116. Returns:
  117. True if this user exists on at least one application service.
  118. """
  119. user_query_services = yield self._get_services_for_user(
  120. user_id=user_id
  121. )
  122. for user_service in user_query_services:
  123. is_known_user = yield self.appservice_api.query_user(
  124. user_service, user_id
  125. )
  126. if is_known_user:
  127. defer.returnValue(True)
  128. defer.returnValue(False)
  129. @defer.inlineCallbacks
  130. def query_room_alias_exists(self, room_alias):
  131. """Check if an application service knows this room alias exists.
  132. Args:
  133. room_alias(RoomAlias): The room alias to query.
  134. Returns:
  135. namedtuple: with keys "room_id" and "servers" or None if no
  136. association can be found.
  137. """
  138. room_alias_str = room_alias.to_string()
  139. services = self.store.get_app_services()
  140. alias_query_services = [
  141. s for s in services if (
  142. s.is_interested_in_alias(room_alias_str)
  143. )
  144. ]
  145. for alias_service in alias_query_services:
  146. is_known_alias = yield self.appservice_api.query_alias(
  147. alias_service, room_alias_str
  148. )
  149. if is_known_alias:
  150. # the alias exists now so don't query more ASes.
  151. result = yield self.store.get_association_from_room_alias(
  152. room_alias
  153. )
  154. defer.returnValue(result)
  155. @defer.inlineCallbacks
  156. def query_3pe(self, kind, protocol, fields):
  157. services = yield self._get_services_for_3pn(protocol)
  158. results = yield make_deferred_yieldable(defer.DeferredList([
  159. run_in_background(
  160. self.appservice_api.query_3pe,
  161. service, kind, protocol, fields,
  162. )
  163. for service in services
  164. ], consumeErrors=True))
  165. ret = []
  166. for (success, result) in results:
  167. if success:
  168. ret.extend(result)
  169. defer.returnValue(ret)
  170. @defer.inlineCallbacks
  171. def get_3pe_protocols(self, only_protocol=None):
  172. services = self.store.get_app_services()
  173. protocols = {}
  174. # Collect up all the individual protocol responses out of the ASes
  175. for s in services:
  176. for p in s.protocols:
  177. if only_protocol is not None and p != only_protocol:
  178. continue
  179. if p not in protocols:
  180. protocols[p] = []
  181. info = yield self.appservice_api.get_3pe_protocol(s, p)
  182. if info is not None:
  183. protocols[p].append(info)
  184. def _merge_instances(infos):
  185. if not infos:
  186. return {}
  187. # Merge the 'instances' lists of multiple results, but just take
  188. # the other fields from the first as they ought to be identical
  189. # copy the result so as not to corrupt the cached one
  190. combined = dict(infos[0])
  191. combined["instances"] = list(combined["instances"])
  192. for info in infos[1:]:
  193. combined["instances"].extend(info["instances"])
  194. return combined
  195. for p in protocols.keys():
  196. protocols[p] = _merge_instances(protocols[p])
  197. defer.returnValue(protocols)
  198. @defer.inlineCallbacks
  199. def _get_services_for_event(self, event):
  200. """Retrieve a list of application services interested in this event.
  201. Args:
  202. event(Event): The event to check. Can be None if alias_list is not.
  203. Returns:
  204. list<ApplicationService>: A list of services interested in this
  205. event based on the service regex.
  206. """
  207. services = self.store.get_app_services()
  208. # we can't use a list comprehension here. Since python 3, list
  209. # comprehensions use a generator internally. This means you can't yield
  210. # inside of a list comprehension anymore.
  211. interested_list = []
  212. for s in services:
  213. if (yield s.is_interested(event, self.store)):
  214. interested_list.append(s)
  215. defer.returnValue(interested_list)
  216. def _get_services_for_user(self, user_id):
  217. services = self.store.get_app_services()
  218. interested_list = [
  219. s for s in services if (
  220. s.is_interested_in_user(user_id)
  221. )
  222. ]
  223. return defer.succeed(interested_list)
  224. def _get_services_for_3pn(self, protocol):
  225. services = self.store.get_app_services()
  226. interested_list = [
  227. s for s in services if s.is_interested_in_protocol(protocol)
  228. ]
  229. return defer.succeed(interested_list)
  230. @defer.inlineCallbacks
  231. def _is_unknown_user(self, user_id):
  232. if not self.is_mine_id(user_id):
  233. # we don't know if they are unknown or not since it isn't one of our
  234. # users. We can't poke ASes.
  235. defer.returnValue(False)
  236. return
  237. user_info = yield self.store.get_user_by_id(user_id)
  238. if user_info:
  239. defer.returnValue(False)
  240. return
  241. # user not found; could be the AS though, so check.
  242. services = self.store.get_app_services()
  243. service_list = [s for s in services if s.sender == user_id]
  244. defer.returnValue(len(service_list) == 0)
  245. @defer.inlineCallbacks
  246. def _check_user_exists(self, user_id):
  247. unknown_user = yield self._is_unknown_user(user_id)
  248. if unknown_user:
  249. exists = yield self.query_user_exists(user_id)
  250. defer.returnValue(exists)
  251. defer.returnValue(True)