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