transactions.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-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. from ._base import SQLBaseStore
  16. from synapse.util.caches.descriptors import cached
  17. from twisted.internet import defer, reactor
  18. from canonicaljson import encode_canonical_json
  19. from collections import namedtuple
  20. import itertools
  21. import logging
  22. logger = logging.getLogger(__name__)
  23. _TransactionRow = namedtuple(
  24. "_TransactionRow", (
  25. "id", "transaction_id", "destination", "ts", "response_code",
  26. "response_json",
  27. )
  28. )
  29. _UpdateTransactionRow = namedtuple(
  30. "_TransactionRow", (
  31. "response_code", "response_json",
  32. )
  33. )
  34. class TransactionStore(SQLBaseStore):
  35. """A collection of queries for handling PDUs.
  36. """
  37. def __init__(self, hs):
  38. super(TransactionStore, self).__init__(hs)
  39. # New transactions that are currently in flights
  40. self.inflight_transactions = {}
  41. # Newly delievered transactions that *weren't* persisted while in flight
  42. self.new_delivered_transactions = {}
  43. # Newly delivered transactions that *were* persisted while in flight
  44. self.update_delivered_transactions = {}
  45. self.last_transaction = {}
  46. reactor.addSystemEventTrigger("before", "shutdown", self._persist_in_mem_txns)
  47. hs.get_clock().looping_call(
  48. self._persist_in_mem_txns,
  49. 1000,
  50. )
  51. def get_received_txn_response(self, transaction_id, origin):
  52. """For an incoming transaction from a given origin, check if we have
  53. already responded to it. If so, return the response code and response
  54. body (as a dict).
  55. Args:
  56. transaction_id (str)
  57. origin(str)
  58. Returns:
  59. tuple: None if we have not previously responded to
  60. this transaction or a 2-tuple of (int, dict)
  61. """
  62. return self.runInteraction(
  63. "get_received_txn_response",
  64. self._get_received_txn_response, transaction_id, origin
  65. )
  66. def _get_received_txn_response(self, txn, transaction_id, origin):
  67. result = self._simple_select_one_txn(
  68. txn,
  69. table="received_transactions",
  70. keyvalues={
  71. "transaction_id": transaction_id,
  72. "origin": origin,
  73. },
  74. retcols=(
  75. "transaction_id", "origin", "ts", "response_code", "response_json",
  76. "has_been_referenced",
  77. ),
  78. allow_none=True,
  79. )
  80. if result and result["response_code"]:
  81. return result["response_code"], result["response_json"]
  82. else:
  83. return None
  84. def set_received_txn_response(self, transaction_id, origin, code,
  85. response_dict):
  86. """Persist the response we returened for an incoming transaction, and
  87. should return for subsequent transactions with the same transaction_id
  88. and origin.
  89. Args:
  90. txn
  91. transaction_id (str)
  92. origin (str)
  93. code (int)
  94. response_json (str)
  95. """
  96. return self._simple_insert(
  97. table="received_transactions",
  98. values={
  99. "transaction_id": transaction_id,
  100. "origin": origin,
  101. "response_code": code,
  102. "response_json": buffer(encode_canonical_json(response_dict)),
  103. },
  104. or_ignore=True,
  105. desc="set_received_txn_response",
  106. )
  107. def prep_send_transaction(self, transaction_id, destination,
  108. origin_server_ts):
  109. """Persists an outgoing transaction and calculates the values for the
  110. previous transaction id list.
  111. This should be called before sending the transaction so that it has the
  112. correct value for the `prev_ids` key.
  113. Args:
  114. transaction_id (str)
  115. destination (str)
  116. origin_server_ts (int)
  117. Returns:
  118. list: A list of previous transaction ids.
  119. """
  120. auto_id = self._transaction_id_gen.get_next()
  121. txn_row = _TransactionRow(
  122. id=auto_id,
  123. transaction_id=transaction_id,
  124. destination=destination,
  125. ts=origin_server_ts,
  126. response_code=0,
  127. response_json=None,
  128. )
  129. self.inflight_transactions.setdefault(destination, {})[transaction_id] = txn_row
  130. prev_txn = self.last_transaction.get(destination)
  131. if prev_txn:
  132. return defer.succeed(prev_txn)
  133. else:
  134. return self.runInteraction(
  135. "_get_prevs_txn",
  136. self._get_prevs_txn,
  137. destination,
  138. )
  139. def _get_prevs_txn(self, txn, destination):
  140. # First we find out what the prev_txns should be.
  141. # Since we know that we are only sending one transaction at a time,
  142. # we can simply take the last one.
  143. query = (
  144. "SELECT * FROM sent_transactions"
  145. " WHERE destination = ?"
  146. " ORDER BY id DESC LIMIT 1"
  147. )
  148. txn.execute(query, (destination,))
  149. results = self.cursor_to_dict(txn)
  150. prev_txns = [r["transaction_id"] for r in results]
  151. return prev_txns
  152. def delivered_txn(self, transaction_id, destination, code, response_dict):
  153. """Persists the response for an outgoing transaction.
  154. Args:
  155. transaction_id (str)
  156. destination (str)
  157. code (int)
  158. response_json (str)
  159. """
  160. txn_row = self.inflight_transactions.get(
  161. destination, {}
  162. ).pop(transaction_id, None)
  163. self.last_transaction[destination] = transaction_id
  164. if txn_row:
  165. d = self.new_delivered_transactions.setdefault(destination, {})
  166. d[transaction_id] = txn_row._replace(
  167. response_code=code,
  168. response_json=None, # For now, don't persist response
  169. )
  170. else:
  171. d = self.update_delivered_transactions.setdefault(destination, {})
  172. # For now, don't persist response
  173. d[transaction_id] = _UpdateTransactionRow(code, None)
  174. def get_transactions_after(self, transaction_id, destination):
  175. """Get all transactions after a given local transaction_id.
  176. Args:
  177. transaction_id (str)
  178. destination (str)
  179. Returns:
  180. list: A list of dicts
  181. """
  182. return self.runInteraction(
  183. "get_transactions_after",
  184. self._get_transactions_after, transaction_id, destination
  185. )
  186. def _get_transactions_after(self, txn, transaction_id, destination):
  187. query = (
  188. "SELECT * FROM sent_transactions"
  189. " WHERE destination = ? AND id >"
  190. " ("
  191. " SELECT id FROM sent_transactions"
  192. " WHERE transaction_id = ? AND destination = ?"
  193. " )"
  194. )
  195. txn.execute(query, (destination, transaction_id, destination))
  196. return self.cursor_to_dict(txn)
  197. @cached()
  198. def get_destination_retry_timings(self, destination):
  199. """Gets the current retry timings (if any) for a given destination.
  200. Args:
  201. destination (str)
  202. Returns:
  203. None if not retrying
  204. Otherwise a dict for the retry scheme
  205. """
  206. return self.runInteraction(
  207. "get_destination_retry_timings",
  208. self._get_destination_retry_timings, destination)
  209. def _get_destination_retry_timings(self, txn, destination):
  210. result = self._simple_select_one_txn(
  211. txn,
  212. table="destinations",
  213. keyvalues={
  214. "destination": destination,
  215. },
  216. retcols=("destination", "retry_last_ts", "retry_interval"),
  217. allow_none=True,
  218. )
  219. if result and result["retry_last_ts"] > 0:
  220. return result
  221. else:
  222. return None
  223. def set_destination_retry_timings(self, destination,
  224. retry_last_ts, retry_interval):
  225. """Sets the current retry timings for a given destination.
  226. Both timings should be zero if retrying is no longer occuring.
  227. Args:
  228. destination (str)
  229. retry_last_ts (int) - time of last retry attempt in unix epoch ms
  230. retry_interval (int) - how long until next retry in ms
  231. """
  232. # XXX: we could chose to not bother persisting this if our cache thinks
  233. # this is a NOOP
  234. return self.runInteraction(
  235. "set_destination_retry_timings",
  236. self._set_destination_retry_timings,
  237. destination,
  238. retry_last_ts,
  239. retry_interval,
  240. )
  241. def _set_destination_retry_timings(self, txn, destination,
  242. retry_last_ts, retry_interval):
  243. txn.call_after(self.get_destination_retry_timings.invalidate, (destination,))
  244. self._simple_upsert_txn(
  245. txn,
  246. "destinations",
  247. keyvalues={
  248. "destination": destination,
  249. },
  250. values={
  251. "retry_last_ts": retry_last_ts,
  252. "retry_interval": retry_interval,
  253. },
  254. insertion_values={
  255. "destination": destination,
  256. "retry_last_ts": retry_last_ts,
  257. "retry_interval": retry_interval,
  258. }
  259. )
  260. def get_destinations_needing_retry(self):
  261. """Get all destinations which are due a retry for sending a transaction.
  262. Returns:
  263. list: A list of dicts
  264. """
  265. return self.runInteraction(
  266. "get_destinations_needing_retry",
  267. self._get_destinations_needing_retry
  268. )
  269. def _get_destinations_needing_retry(self, txn):
  270. query = (
  271. "SELECT * FROM destinations"
  272. " WHERE retry_last_ts > 0 and retry_next_ts < ?"
  273. )
  274. txn.execute(query, (self._clock.time_msec(),))
  275. return self.cursor_to_dict(txn)
  276. @defer.inlineCallbacks
  277. def _persist_in_mem_txns(self):
  278. try:
  279. inflight = self.inflight_transactions
  280. new_delivered = self.new_delivered_transactions
  281. update_delivered = self.update_delivered_transactions
  282. self.inflight_transactions = {}
  283. self.new_delivered_transactions = {}
  284. self.update_delivered_transactions = {}
  285. full_rows = [
  286. row._asdict()
  287. for txn_map in itertools.chain(inflight.values(), new_delivered.values())
  288. for row in txn_map.values()
  289. ]
  290. def f(txn):
  291. if full_rows:
  292. self._simple_insert_many_txn(
  293. txn=txn,
  294. table="sent_transactions",
  295. values=full_rows
  296. )
  297. for dest, txn_map in update_delivered.items():
  298. for txn_id, update_row in txn_map.items():
  299. self._simple_update_one_txn(
  300. txn,
  301. table="sent_transactions",
  302. keyvalues={
  303. "transaction_id": txn_id,
  304. "destination": dest,
  305. },
  306. updatevalues={
  307. "response_code": update_row.response_code,
  308. "response_json": None, # For now, don't persist response
  309. }
  310. )
  311. if full_rows or update_delivered:
  312. yield self.runInteraction("_persist_in_mem_txns", f)
  313. except:
  314. logger.exception("Failed to persist transactions!")