appservice.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015, 2016 OpenMarket Ltd
  3. # Copyright 2018 New Vector Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import logging
  17. import re
  18. import simplejson as json
  19. from twisted.internet import defer
  20. from synapse.appservice import AppServiceTransaction
  21. from synapse.config.appservice import load_appservices
  22. from synapse.storage.events import EventsWorkerStore
  23. from ._base import SQLBaseStore
  24. logger = logging.getLogger(__name__)
  25. def _make_exclusive_regex(services_cache):
  26. # We precompie a regex constructed from all the regexes that the AS's
  27. # have registered for exclusive users.
  28. exclusive_user_regexes = [
  29. regex.pattern
  30. for service in services_cache
  31. for regex in service.get_exlusive_user_regexes()
  32. ]
  33. if exclusive_user_regexes:
  34. exclusive_user_regex = "|".join("(" + r + ")" for r in exclusive_user_regexes)
  35. exclusive_user_regex = re.compile(exclusive_user_regex)
  36. else:
  37. # We handle this case specially otherwise the constructed regex
  38. # will always match
  39. exclusive_user_regex = None
  40. return exclusive_user_regex
  41. class ApplicationServiceWorkerStore(SQLBaseStore):
  42. def __init__(self, db_conn, hs):
  43. self.services_cache = load_appservices(
  44. hs.hostname,
  45. hs.config.app_service_config_files
  46. )
  47. self.exclusive_user_regex = _make_exclusive_regex(self.services_cache)
  48. super(ApplicationServiceWorkerStore, self).__init__(db_conn, hs)
  49. def get_app_services(self):
  50. return self.services_cache
  51. def get_if_app_services_interested_in_user(self, user_id):
  52. """Check if the user is one associated with an app service (exclusively)
  53. """
  54. if self.exclusive_user_regex:
  55. return bool(self.exclusive_user_regex.match(user_id))
  56. else:
  57. return False
  58. def get_app_service_by_user_id(self, user_id):
  59. """Retrieve an application service from their user ID.
  60. All application services have associated with them a particular user ID.
  61. There is no distinguishing feature on the user ID which indicates it
  62. represents an application service. This function allows you to map from
  63. a user ID to an application service.
  64. Args:
  65. user_id(str): The user ID to see if it is an application service.
  66. Returns:
  67. synapse.appservice.ApplicationService or None.
  68. """
  69. for service in self.services_cache:
  70. if service.sender == user_id:
  71. return service
  72. return None
  73. def get_app_service_by_token(self, token):
  74. """Get the application service with the given appservice token.
  75. Args:
  76. token (str): The application service token.
  77. Returns:
  78. synapse.appservice.ApplicationService or None.
  79. """
  80. for service in self.services_cache:
  81. if service.token == token:
  82. return service
  83. return None
  84. def get_app_service_by_id(self, as_id):
  85. """Get the application service with the given appservice ID.
  86. Args:
  87. as_id (str): The application service ID.
  88. Returns:
  89. synapse.appservice.ApplicationService or None.
  90. """
  91. for service in self.services_cache:
  92. if service.id == as_id:
  93. return service
  94. return None
  95. class ApplicationServiceStore(ApplicationServiceWorkerStore):
  96. # This is currently empty due to there not being any AS storage functions
  97. # that can't be run on the workers. Since this may change in future, and
  98. # to keep consistency with the other stores, we keep this empty class for
  99. # now.
  100. pass
  101. class ApplicationServiceTransactionWorkerStore(ApplicationServiceWorkerStore,
  102. EventsWorkerStore):
  103. @defer.inlineCallbacks
  104. def get_appservices_by_state(self, state):
  105. """Get a list of application services based on their state.
  106. Args:
  107. state(ApplicationServiceState): The state to filter on.
  108. Returns:
  109. A Deferred which resolves to a list of ApplicationServices, which
  110. may be empty.
  111. """
  112. results = yield self._simple_select_list(
  113. "application_services_state",
  114. dict(state=state),
  115. ["as_id"]
  116. )
  117. # NB: This assumes this class is linked with ApplicationServiceStore
  118. as_list = self.get_app_services()
  119. services = []
  120. for res in results:
  121. for service in as_list:
  122. if service.id == res["as_id"]:
  123. services.append(service)
  124. defer.returnValue(services)
  125. @defer.inlineCallbacks
  126. def get_appservice_state(self, service):
  127. """Get the application service state.
  128. Args:
  129. service(ApplicationService): The service whose state to set.
  130. Returns:
  131. A Deferred which resolves to ApplicationServiceState.
  132. """
  133. result = yield self._simple_select_one(
  134. "application_services_state",
  135. dict(as_id=service.id),
  136. ["state"],
  137. allow_none=True,
  138. desc="get_appservice_state",
  139. )
  140. if result:
  141. defer.returnValue(result.get("state"))
  142. return
  143. defer.returnValue(None)
  144. def set_appservice_state(self, service, state):
  145. """Set the application service state.
  146. Args:
  147. service(ApplicationService): The service whose state to set.
  148. state(ApplicationServiceState): The connectivity state to apply.
  149. Returns:
  150. A Deferred which resolves when the state was set successfully.
  151. """
  152. return self._simple_upsert(
  153. "application_services_state",
  154. dict(as_id=service.id),
  155. dict(state=state)
  156. )
  157. def create_appservice_txn(self, service, events):
  158. """Atomically creates a new transaction for this application service
  159. with the given list of events.
  160. Args:
  161. service(ApplicationService): The service who the transaction is for.
  162. events(list<Event>): A list of events to put in the transaction.
  163. Returns:
  164. AppServiceTransaction: A new transaction.
  165. """
  166. def _create_appservice_txn(txn):
  167. # work out new txn id (highest txn id for this service += 1)
  168. # The highest id may be the last one sent (in which case it is last_txn)
  169. # or it may be the highest in the txns list (which are waiting to be/are
  170. # being sent)
  171. last_txn_id = self._get_last_txn(txn, service.id)
  172. txn.execute(
  173. "SELECT MAX(txn_id) FROM application_services_txns WHERE as_id=?",
  174. (service.id,)
  175. )
  176. highest_txn_id = txn.fetchone()[0]
  177. if highest_txn_id is None:
  178. highest_txn_id = 0
  179. new_txn_id = max(highest_txn_id, last_txn_id) + 1
  180. # Insert new txn into txn table
  181. event_ids = json.dumps([e.event_id for e in events])
  182. txn.execute(
  183. "INSERT INTO application_services_txns(as_id, txn_id, event_ids) "
  184. "VALUES(?,?,?)",
  185. (service.id, new_txn_id, event_ids)
  186. )
  187. return AppServiceTransaction(
  188. service=service, id=new_txn_id, events=events
  189. )
  190. return self.runInteraction(
  191. "create_appservice_txn",
  192. _create_appservice_txn,
  193. )
  194. def complete_appservice_txn(self, txn_id, service):
  195. """Completes an application service transaction.
  196. Args:
  197. txn_id(str): The transaction ID being completed.
  198. service(ApplicationService): The application service which was sent
  199. this transaction.
  200. Returns:
  201. A Deferred which resolves if this transaction was stored
  202. successfully.
  203. """
  204. txn_id = int(txn_id)
  205. def _complete_appservice_txn(txn):
  206. # Debugging query: Make sure the txn being completed is EXACTLY +1 from
  207. # what was there before. If it isn't, we've got problems (e.g. the AS
  208. # has probably missed some events), so whine loudly but still continue,
  209. # since it shouldn't fail completion of the transaction.
  210. last_txn_id = self._get_last_txn(txn, service.id)
  211. if (last_txn_id + 1) != txn_id:
  212. logger.error(
  213. "appservice: Completing a transaction which has an ID > 1 from "
  214. "the last ID sent to this AS. We've either dropped events or "
  215. "sent it to the AS out of order. FIX ME. last_txn=%s "
  216. "completing_txn=%s service_id=%s", last_txn_id, txn_id,
  217. service.id
  218. )
  219. # Set current txn_id for AS to 'txn_id'
  220. self._simple_upsert_txn(
  221. txn, "application_services_state", dict(as_id=service.id),
  222. dict(last_txn=txn_id)
  223. )
  224. # Delete txn
  225. self._simple_delete_txn(
  226. txn, "application_services_txns",
  227. dict(txn_id=txn_id, as_id=service.id)
  228. )
  229. return self.runInteraction(
  230. "complete_appservice_txn",
  231. _complete_appservice_txn,
  232. )
  233. @defer.inlineCallbacks
  234. def get_oldest_unsent_txn(self, service):
  235. """Get the oldest transaction which has not been sent for this
  236. service.
  237. Args:
  238. service(ApplicationService): The app service to get the oldest txn.
  239. Returns:
  240. A Deferred which resolves to an AppServiceTransaction or
  241. None.
  242. """
  243. def _get_oldest_unsent_txn(txn):
  244. # Monotonically increasing txn ids, so just select the smallest
  245. # one in the txns table (we delete them when they are sent)
  246. txn.execute(
  247. "SELECT * FROM application_services_txns WHERE as_id=?"
  248. " ORDER BY txn_id ASC LIMIT 1",
  249. (service.id,)
  250. )
  251. rows = self.cursor_to_dict(txn)
  252. if not rows:
  253. return None
  254. entry = rows[0]
  255. return entry
  256. entry = yield self.runInteraction(
  257. "get_oldest_unsent_appservice_txn",
  258. _get_oldest_unsent_txn,
  259. )
  260. if not entry:
  261. defer.returnValue(None)
  262. event_ids = json.loads(entry["event_ids"])
  263. events = yield self._get_events(event_ids)
  264. defer.returnValue(AppServiceTransaction(
  265. service=service, id=entry["txn_id"], events=events
  266. ))
  267. def _get_last_txn(self, txn, service_id):
  268. txn.execute(
  269. "SELECT last_txn FROM application_services_state WHERE as_id=?",
  270. (service_id,)
  271. )
  272. last_txn_id = txn.fetchone()
  273. if last_txn_id is None or last_txn_id[0] is None: # no row exists
  274. return 0
  275. else:
  276. return int(last_txn_id[0]) # select 'last_txn' col
  277. def set_appservice_last_pos(self, pos):
  278. def set_appservice_last_pos_txn(txn):
  279. txn.execute(
  280. "UPDATE appservice_stream_position SET stream_ordering = ?", (pos,)
  281. )
  282. return self.runInteraction(
  283. "set_appservice_last_pos", set_appservice_last_pos_txn
  284. )
  285. @defer.inlineCallbacks
  286. def get_new_events_for_appservice(self, current_id, limit):
  287. """Get all new evnets"""
  288. def get_new_events_for_appservice_txn(txn):
  289. sql = (
  290. "SELECT e.stream_ordering, e.event_id"
  291. " FROM events AS e"
  292. " WHERE"
  293. " (SELECT stream_ordering FROM appservice_stream_position)"
  294. " < e.stream_ordering"
  295. " AND e.stream_ordering <= ?"
  296. " ORDER BY e.stream_ordering ASC"
  297. " LIMIT ?"
  298. )
  299. txn.execute(sql, (current_id, limit))
  300. rows = txn.fetchall()
  301. upper_bound = current_id
  302. if len(rows) == limit:
  303. upper_bound = rows[-1][0]
  304. return upper_bound, [row[1] for row in rows]
  305. upper_bound, event_ids = yield self.runInteraction(
  306. "get_new_events_for_appservice", get_new_events_for_appservice_txn,
  307. )
  308. events = yield self._get_events(event_ids)
  309. defer.returnValue((upper_bound, events))
  310. class ApplicationServiceTransactionStore(ApplicationServiceTransactionWorkerStore):
  311. # This is currently empty due to there not being any AS storage functions
  312. # that can't be run on the workers. Since this may change in future, and
  313. # to keep consistency with the other stores, we keep this empty class for
  314. # now.
  315. pass