transactions.py 8.5 KB

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