appservice.py 14 KB

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