transactions.py 8.7 KB

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