transactions.py 4.2 KB

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