transactions.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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
  18. import six
  19. from canonicaljson import encode_canonical_json
  20. from collections import namedtuple
  21. import logging
  22. import simplejson as json
  23. # py2 sqlite has buffer hardcoded as only binary type, so we must use it,
  24. # despite being deprecated and removed in favor of memoryview
  25. if six.PY2:
  26. db_binary_type = buffer
  27. else:
  28. db_binary_type = memoryview
  29. logger = logging.getLogger(__name__)
  30. _TransactionRow = namedtuple(
  31. "_TransactionRow", (
  32. "id", "transaction_id", "destination", "ts", "response_code",
  33. "response_json",
  34. )
  35. )
  36. _UpdateTransactionRow = namedtuple(
  37. "_TransactionRow", (
  38. "response_code", "response_json",
  39. )
  40. )
  41. class TransactionStore(SQLBaseStore):
  42. """A collection of queries for handling PDUs.
  43. """
  44. def __init__(self, db_conn, hs):
  45. super(TransactionStore, self).__init__(db_conn, hs)
  46. self._clock.looping_call(self._cleanup_transactions, 30 * 60 * 1000)
  47. def get_received_txn_response(self, transaction_id, origin):
  48. """For an incoming transaction from a given origin, check if we have
  49. already responded to it. If so, return the response code and response
  50. body (as a dict).
  51. Args:
  52. transaction_id (str)
  53. origin(str)
  54. Returns:
  55. tuple: None if we have not previously responded to
  56. this transaction or a 2-tuple of (int, dict)
  57. """
  58. return self.runInteraction(
  59. "get_received_txn_response",
  60. self._get_received_txn_response, transaction_id, origin
  61. )
  62. def _get_received_txn_response(self, txn, transaction_id, origin):
  63. result = self._simple_select_one_txn(
  64. txn,
  65. table="received_transactions",
  66. keyvalues={
  67. "transaction_id": transaction_id,
  68. "origin": origin,
  69. },
  70. retcols=(
  71. "transaction_id", "origin", "ts", "response_code", "response_json",
  72. "has_been_referenced",
  73. ),
  74. allow_none=True,
  75. )
  76. if result and result["response_code"]:
  77. return result["response_code"], json.loads(str(result["response_json"]))
  78. else:
  79. return None
  80. def set_received_txn_response(self, transaction_id, origin, code,
  81. response_dict):
  82. """Persist the response we returened for an incoming transaction, and
  83. should return for subsequent transactions with the same transaction_id
  84. and origin.
  85. Args:
  86. txn
  87. transaction_id (str)
  88. origin (str)
  89. code (int)
  90. response_json (str)
  91. """
  92. return self._simple_insert(
  93. table="received_transactions",
  94. values={
  95. "transaction_id": transaction_id,
  96. "origin": origin,
  97. "response_code": code,
  98. "response_json": db_binary_type(encode_canonical_json(response_dict)),
  99. "ts": self._clock.time_msec(),
  100. },
  101. or_ignore=True,
  102. desc="set_received_txn_response",
  103. )
  104. def prep_send_transaction(self, transaction_id, destination,
  105. origin_server_ts):
  106. """Persists an outgoing transaction and calculates the values for the
  107. previous transaction id list.
  108. This should be called before sending the transaction so that it has the
  109. correct value for the `prev_ids` key.
  110. Args:
  111. transaction_id (str)
  112. destination (str)
  113. origin_server_ts (int)
  114. Returns:
  115. list: A list of previous transaction ids.
  116. """
  117. return defer.succeed([])
  118. def delivered_txn(self, transaction_id, destination, code, response_dict):
  119. """Persists the response for an outgoing transaction.
  120. Args:
  121. transaction_id (str)
  122. destination (str)
  123. code (int)
  124. response_json (str)
  125. """
  126. pass
  127. @cached(max_entries=10000)
  128. def get_destination_retry_timings(self, destination):
  129. """Gets the current retry timings (if any) for a given destination.
  130. Args:
  131. destination (str)
  132. Returns:
  133. None if not retrying
  134. Otherwise a dict for the retry scheme
  135. """
  136. return self.runInteraction(
  137. "get_destination_retry_timings",
  138. self._get_destination_retry_timings, destination)
  139. def _get_destination_retry_timings(self, txn, destination):
  140. result = self._simple_select_one_txn(
  141. txn,
  142. table="destinations",
  143. keyvalues={
  144. "destination": destination,
  145. },
  146. retcols=("destination", "retry_last_ts", "retry_interval"),
  147. allow_none=True,
  148. )
  149. if result and result["retry_last_ts"] > 0:
  150. return result
  151. else:
  152. return None
  153. def set_destination_retry_timings(self, destination,
  154. retry_last_ts, retry_interval):
  155. """Sets the current retry timings for a given destination.
  156. Both timings should be zero if retrying is no longer occuring.
  157. Args:
  158. destination (str)
  159. retry_last_ts (int) - time of last retry attempt in unix epoch ms
  160. retry_interval (int) - how long until next retry in ms
  161. """
  162. # XXX: we could chose to not bother persisting this if our cache thinks
  163. # this is a NOOP
  164. return self.runInteraction(
  165. "set_destination_retry_timings",
  166. self._set_destination_retry_timings,
  167. destination,
  168. retry_last_ts,
  169. retry_interval,
  170. )
  171. def _set_destination_retry_timings(self, txn, destination,
  172. retry_last_ts, retry_interval):
  173. self.database_engine.lock_table(txn, "destinations")
  174. self._invalidate_cache_and_stream(
  175. txn, self.get_destination_retry_timings, (destination,)
  176. )
  177. # We need to be careful here as the data may have changed from under us
  178. # due to a worker setting the timings.
  179. prev_row = self._simple_select_one_txn(
  180. txn,
  181. table="destinations",
  182. keyvalues={
  183. "destination": destination,
  184. },
  185. retcols=("retry_last_ts", "retry_interval"),
  186. allow_none=True,
  187. )
  188. if not prev_row:
  189. self._simple_insert_txn(
  190. txn,
  191. table="destinations",
  192. values={
  193. "destination": destination,
  194. "retry_last_ts": retry_last_ts,
  195. "retry_interval": retry_interval,
  196. }
  197. )
  198. elif retry_interval == 0 or prev_row["retry_interval"] < retry_interval:
  199. self._simple_update_one_txn(
  200. txn,
  201. "destinations",
  202. keyvalues={
  203. "destination": destination,
  204. },
  205. updatevalues={
  206. "retry_last_ts": retry_last_ts,
  207. "retry_interval": retry_interval,
  208. },
  209. )
  210. def get_destinations_needing_retry(self):
  211. """Get all destinations which are due a retry for sending a transaction.
  212. Returns:
  213. list: A list of dicts
  214. """
  215. return self.runInteraction(
  216. "get_destinations_needing_retry",
  217. self._get_destinations_needing_retry
  218. )
  219. def _get_destinations_needing_retry(self, txn):
  220. query = (
  221. "SELECT * FROM destinations"
  222. " WHERE retry_last_ts > 0 and retry_next_ts < ?"
  223. )
  224. txn.execute(query, (self._clock.time_msec(),))
  225. return self.cursor_to_dict(txn)
  226. def _cleanup_transactions(self):
  227. now = self._clock.time_msec()
  228. month_ago = now - 30 * 24 * 60 * 60 * 1000
  229. def _cleanup_transactions_txn(txn):
  230. txn.execute("DELETE FROM received_transactions WHERE ts < ?", (month_ago,))
  231. return self.runInteraction("_cleanup_transactions", _cleanup_transactions_txn)