appservice.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. import simplejson as json
  17. from twisted.internet import defer
  18. from synapse.api.constants import Membership
  19. from synapse.appservice import AppServiceTransaction
  20. from synapse.config.appservice import load_appservices
  21. from synapse.storage.roommember import RoomsForUser
  22. from ._base import SQLBaseStore
  23. logger = logging.getLogger(__name__)
  24. class ApplicationServiceStore(SQLBaseStore):
  25. def __init__(self, hs):
  26. super(ApplicationServiceStore, self).__init__(hs)
  27. self.hostname = hs.hostname
  28. self.services_cache = load_appservices(
  29. hs.hostname,
  30. hs.config.app_service_config_files
  31. )
  32. def get_app_services(self):
  33. return defer.succeed(self.services_cache)
  34. def get_app_service_by_user_id(self, user_id):
  35. """Retrieve an application service from their user ID.
  36. All application services have associated with them a particular user ID.
  37. There is no distinguishing feature on the user ID which indicates it
  38. represents an application service. This function allows you to map from
  39. a user ID to an application service.
  40. Args:
  41. user_id(str): The user ID to see if it is an application service.
  42. Returns:
  43. synapse.appservice.ApplicationService or None.
  44. """
  45. for service in self.services_cache:
  46. if service.sender == user_id:
  47. return defer.succeed(service)
  48. return defer.succeed(None)
  49. def get_app_service_by_token(self, token):
  50. """Get the application service with the given appservice token.
  51. Args:
  52. token (str): The application service token.
  53. Returns:
  54. synapse.appservice.ApplicationService or None.
  55. """
  56. for service in self.services_cache:
  57. if service.token == token:
  58. return defer.succeed(service)
  59. return defer.succeed(None)
  60. def get_app_service_rooms(self, service):
  61. """Get a list of RoomsForUser for this application service.
  62. Application services may be "interested" in lots of rooms depending on
  63. the room ID, the room aliases, or the members in the room. This function
  64. takes all of these into account and returns a list of RoomsForUser which
  65. represent the entire list of room IDs that this application service
  66. wants to know about.
  67. Args:
  68. service: The application service to get a room list for.
  69. Returns:
  70. A list of RoomsForUser.
  71. """
  72. return self.runInteraction(
  73. "get_app_service_rooms",
  74. self._get_app_service_rooms_txn,
  75. service,
  76. )
  77. def _get_app_service_rooms_txn(self, txn, service):
  78. # get all rooms matching the room ID regex.
  79. room_entries = self._simple_select_list_txn(
  80. txn=txn, table="rooms", keyvalues=None, retcols=["room_id"]
  81. )
  82. matching_room_list = set([
  83. r["room_id"] for r in room_entries if
  84. service.is_interested_in_room(r["room_id"])
  85. ])
  86. # resolve room IDs for matching room alias regex.
  87. room_alias_mappings = self._simple_select_list_txn(
  88. txn=txn, table="room_aliases", keyvalues=None,
  89. retcols=["room_id", "room_alias"]
  90. )
  91. matching_room_list |= set([
  92. r["room_id"] for r in room_alias_mappings if
  93. service.is_interested_in_alias(r["room_alias"])
  94. ])
  95. # get all rooms for every user for this AS. This is scoped to users on
  96. # this HS only.
  97. user_list = self._simple_select_list_txn(
  98. txn=txn, table="users", keyvalues=None, retcols=["name"]
  99. )
  100. user_list = [
  101. u["name"] for u in user_list if
  102. service.is_interested_in_user(u["name"])
  103. ]
  104. rooms_for_user_matching_user_id = set() # RoomsForUser list
  105. for user_id in user_list:
  106. # FIXME: This assumes this store is linked with RoomMemberStore :(
  107. rooms_for_user = self._get_rooms_for_user_where_membership_is_txn(
  108. txn=txn,
  109. user_id=user_id,
  110. membership_list=[Membership.JOIN]
  111. )
  112. rooms_for_user_matching_user_id |= set(rooms_for_user)
  113. # make RoomsForUser tuples for room ids and aliases which are not in the
  114. # main rooms_for_user_list - e.g. they are rooms which do not have AS
  115. # registered users in it.
  116. known_room_ids = [r.room_id for r in rooms_for_user_matching_user_id]
  117. missing_rooms_for_user = [
  118. RoomsForUser(r, service.sender, "join") for r in
  119. matching_room_list if r not in known_room_ids
  120. ]
  121. rooms_for_user_matching_user_id |= set(missing_rooms_for_user)
  122. return rooms_for_user_matching_user_id
  123. class ApplicationServiceTransactionStore(SQLBaseStore):
  124. def __init__(self, hs):
  125. super(ApplicationServiceTransactionStore, self).__init__(hs)
  126. @defer.inlineCallbacks
  127. def get_appservices_by_state(self, state):
  128. """Get a list of application services based on their state.
  129. Args:
  130. state(ApplicationServiceState): The state to filter on.
  131. Returns:
  132. A Deferred which resolves to a list of ApplicationServices, which
  133. may be empty.
  134. """
  135. results = yield self._simple_select_list(
  136. "application_services_state",
  137. dict(state=state),
  138. ["as_id"]
  139. )
  140. # NB: This assumes this class is linked with ApplicationServiceStore
  141. as_list = yield self.get_app_services()
  142. services = []
  143. for res in results:
  144. for service in as_list:
  145. if service.id == res["as_id"]:
  146. services.append(service)
  147. defer.returnValue(services)
  148. @defer.inlineCallbacks
  149. def get_appservice_state(self, service):
  150. """Get the application service state.
  151. Args:
  152. service(ApplicationService): The service whose state to set.
  153. Returns:
  154. A Deferred which resolves to ApplicationServiceState.
  155. """
  156. result = yield self._simple_select_one(
  157. "application_services_state",
  158. dict(as_id=service.id),
  159. ["state"],
  160. allow_none=True,
  161. desc="get_appservice_state",
  162. )
  163. if result:
  164. defer.returnValue(result.get("state"))
  165. return
  166. defer.returnValue(None)
  167. def set_appservice_state(self, service, state):
  168. """Set the application service state.
  169. Args:
  170. service(ApplicationService): The service whose state to set.
  171. state(ApplicationServiceState): The connectivity state to apply.
  172. Returns:
  173. A Deferred which resolves when the state was set successfully.
  174. """
  175. return self._simple_upsert(
  176. "application_services_state",
  177. dict(as_id=service.id),
  178. dict(state=state)
  179. )
  180. def create_appservice_txn(self, service, events):
  181. """Atomically creates a new transaction for this application service
  182. with the given list of events.
  183. Args:
  184. service(ApplicationService): The service who the transaction is for.
  185. events(list<Event>): A list of events to put in the transaction.
  186. Returns:
  187. AppServiceTransaction: A new transaction.
  188. """
  189. return self.runInteraction(
  190. "create_appservice_txn",
  191. self._create_appservice_txn,
  192. service, events
  193. )
  194. def _create_appservice_txn(self, txn, service, events):
  195. # work out new txn id (highest txn id for this service += 1)
  196. # The highest id may be the last one sent (in which case it is last_txn)
  197. # or it may be the highest in the txns list (which are waiting to be/are
  198. # being sent)
  199. last_txn_id = self._get_last_txn(txn, service.id)
  200. txn.execute(
  201. "SELECT MAX(txn_id) FROM application_services_txns WHERE as_id=?",
  202. (service.id,)
  203. )
  204. highest_txn_id = txn.fetchone()[0]
  205. if highest_txn_id is None:
  206. highest_txn_id = 0
  207. new_txn_id = max(highest_txn_id, last_txn_id) + 1
  208. # Insert new txn into txn table
  209. event_ids = json.dumps([e.event_id for e in events])
  210. txn.execute(
  211. "INSERT INTO application_services_txns(as_id, txn_id, event_ids) "
  212. "VALUES(?,?,?)",
  213. (service.id, new_txn_id, event_ids)
  214. )
  215. return AppServiceTransaction(
  216. service=service, id=new_txn_id, events=events
  217. )
  218. def complete_appservice_txn(self, txn_id, service):
  219. """Completes an application service transaction.
  220. Args:
  221. txn_id(str): The transaction ID being completed.
  222. service(ApplicationService): The application service which was sent
  223. this transaction.
  224. Returns:
  225. A Deferred which resolves if this transaction was stored
  226. successfully.
  227. """
  228. return self.runInteraction(
  229. "complete_appservice_txn",
  230. self._complete_appservice_txn,
  231. txn_id, service
  232. )
  233. def _complete_appservice_txn(self, txn, txn_id, service):
  234. txn_id = int(txn_id)
  235. # Debugging query: Make sure the txn being completed is EXACTLY +1 from
  236. # what was there before. If it isn't, we've got problems (e.g. the AS
  237. # has probably missed some events), so whine loudly but still continue,
  238. # since it shouldn't fail completion of the transaction.
  239. last_txn_id = self._get_last_txn(txn, service.id)
  240. if (last_txn_id + 1) != txn_id:
  241. logger.error(
  242. "appservice: Completing a transaction which has an ID > 1 from "
  243. "the last ID sent to this AS. We've either dropped events or "
  244. "sent it to the AS out of order. FIX ME. last_txn=%s "
  245. "completing_txn=%s service_id=%s", last_txn_id, txn_id,
  246. service.id
  247. )
  248. # Set current txn_id for AS to 'txn_id'
  249. self._simple_upsert_txn(
  250. txn, "application_services_state", dict(as_id=service.id),
  251. dict(last_txn=txn_id)
  252. )
  253. # Delete txn
  254. self._simple_delete_txn(
  255. txn, "application_services_txns",
  256. dict(txn_id=txn_id, as_id=service.id)
  257. )
  258. @defer.inlineCallbacks
  259. def get_oldest_unsent_txn(self, service):
  260. """Get the oldest transaction which has not been sent for this
  261. service.
  262. Args:
  263. service(ApplicationService): The app service to get the oldest txn.
  264. Returns:
  265. A Deferred which resolves to an AppServiceTransaction or
  266. None.
  267. """
  268. entry = yield self.runInteraction(
  269. "get_oldest_unsent_appservice_txn",
  270. self._get_oldest_unsent_txn,
  271. service
  272. )
  273. if not entry:
  274. defer.returnValue(None)
  275. event_ids = json.loads(entry["event_ids"])
  276. events = yield self.get_events(event_ids)
  277. defer.returnValue(AppServiceTransaction(
  278. service=service, id=entry["txn_id"], events=events
  279. ))
  280. def _get_oldest_unsent_txn(self, txn, service):
  281. # Monotonically increasing txn ids, so just select the smallest
  282. # one in the txns table (we delete them when they are sent)
  283. txn.execute(
  284. "SELECT * FROM application_services_txns WHERE as_id=?"
  285. " ORDER BY txn_id ASC LIMIT 1",
  286. (service.id,)
  287. )
  288. rows = self.cursor_to_dict(txn)
  289. if not rows:
  290. return None
  291. entry = rows[0]
  292. return entry
  293. def _get_last_txn(self, txn, service_id):
  294. txn.execute(
  295. "SELECT last_txn FROM application_services_state WHERE as_id=?",
  296. (service_id,)
  297. )
  298. last_txn_id = txn.fetchone()
  299. if last_txn_id is None or last_txn_id[0] is None: # no row exists
  300. return 0
  301. else:
  302. return int(last_txn_id[0]) # select 'last_txn' col