transactions.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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. """This module contains logic for storing HTTP PUT transactions. This is used
  16. to ensure idempotency when performing PUTs using the REST API."""
  17. import logging
  18. from synapse.logging.context import make_deferred_yieldable, run_in_background
  19. from synapse.util.async_helpers import ObservableDeferred
  20. logger = logging.getLogger(__name__)
  21. CLEANUP_PERIOD_MS = 1000 * 60 * 30 # 30 mins
  22. class HttpTransactionCache(object):
  23. def __init__(self, hs):
  24. self.hs = hs
  25. self.auth = self.hs.get_auth()
  26. self.clock = self.hs.get_clock()
  27. self.transactions = {
  28. # $txn_key: (ObservableDeferred<(res_code, res_json_body)>, timestamp)
  29. }
  30. # Try to clean entries every 30 mins. This means entries will exist
  31. # for at *LEAST* 30 mins, and at *MOST* 60 mins.
  32. self.cleaner = self.clock.looping_call(self._cleanup, CLEANUP_PERIOD_MS)
  33. def _get_transaction_key(self, request):
  34. """A helper function which returns a transaction key that can be used
  35. with TransactionCache for idempotent requests.
  36. Idempotency is based on the returned key being the same for separate
  37. requests to the same endpoint. The key is formed from the HTTP request
  38. path and the access_token for the requesting user.
  39. Args:
  40. request (twisted.web.http.Request): The incoming request. Must
  41. contain an access_token.
  42. Returns:
  43. str: A transaction key
  44. """
  45. token = self.auth.get_access_token_from_request(request)
  46. return request.path.decode("utf8") + "/" + token
  47. def fetch_or_execute_request(self, request, fn, *args, **kwargs):
  48. """A helper function for fetch_or_execute which extracts
  49. a transaction key from the given request.
  50. See:
  51. fetch_or_execute
  52. """
  53. return self.fetch_or_execute(
  54. self._get_transaction_key(request), fn, *args, **kwargs
  55. )
  56. def fetch_or_execute(self, txn_key, fn, *args, **kwargs):
  57. """Fetches the response for this transaction, or executes the given function
  58. to produce a response for this transaction.
  59. Args:
  60. txn_key (str): A key to ensure idempotency should fetch_or_execute be
  61. called again at a later point in time.
  62. fn (function): A function which returns a tuple of
  63. (response_code, response_dict).
  64. *args: Arguments to pass to fn.
  65. **kwargs: Keyword arguments to pass to fn.
  66. Returns:
  67. Deferred which resolves to a tuple of (response_code, response_dict).
  68. """
  69. if txn_key in self.transactions:
  70. observable = self.transactions[txn_key][0]
  71. else:
  72. # execute the function instead.
  73. deferred = run_in_background(fn, *args, **kwargs)
  74. observable = ObservableDeferred(deferred)
  75. self.transactions[txn_key] = (observable, self.clock.time_msec())
  76. # if the request fails with an exception, remove it
  77. # from the transaction map. This is done to ensure that we don't
  78. # cache transient errors like rate-limiting errors, etc.
  79. def remove_from_map(err):
  80. self.transactions.pop(txn_key, None)
  81. # we deliberately do not propagate the error any further, as we
  82. # expect the observers to have reported it.
  83. deferred.addErrback(remove_from_map)
  84. return make_deferred_yieldable(observable.observe())
  85. def _cleanup(self):
  86. now = self.clock.time_msec()
  87. for key in list(self.transactions):
  88. ts = self.transactions[key][1]
  89. if now > (ts + CLEANUP_PERIOD_MS): # after cleanup period
  90. del self.transactions[key]