You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

134 lines
5.0 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """This module contains logic for storing HTTP PUT transactions. This is used
  15. to ensure idempotency when performing PUTs using the REST API."""
  16. import logging
  17. from typing import TYPE_CHECKING, Awaitable, Callable, Dict, Tuple
  18. from typing_extensions import ParamSpec
  19. from twisted.internet.defer import Deferred
  20. from twisted.python.failure import Failure
  21. from twisted.web.server import Request
  22. from synapse.logging.context import make_deferred_yieldable, run_in_background
  23. from synapse.types import JsonDict
  24. from synapse.util.async_helpers import ObservableDeferred
  25. if TYPE_CHECKING:
  26. from synapse.server import HomeServer
  27. logger = logging.getLogger(__name__)
  28. CLEANUP_PERIOD_MS = 1000 * 60 * 30 # 30 mins
  29. P = ParamSpec("P")
  30. class HttpTransactionCache:
  31. def __init__(self, hs: "HomeServer"):
  32. self.hs = hs
  33. self.auth = self.hs.get_auth()
  34. self.clock = self.hs.get_clock()
  35. # $txn_key: (ObservableDeferred<(res_code, res_json_body)>, timestamp)
  36. self.transactions: Dict[
  37. str, Tuple[ObservableDeferred[Tuple[int, JsonDict]], int]
  38. ] = {}
  39. # Try to clean entries every 30 mins. This means entries will exist
  40. # for at *LEAST* 30 mins, and at *MOST* 60 mins.
  41. self.cleaner = self.clock.looping_call(self._cleanup, CLEANUP_PERIOD_MS)
  42. def _get_transaction_key(self, request: Request) -> str:
  43. """A helper function which returns a transaction key that can be used
  44. with TransactionCache for idempotent requests.
  45. Idempotency is based on the returned key being the same for separate
  46. requests to the same endpoint. The key is formed from the HTTP request
  47. path and the access_token for the requesting user.
  48. Args:
  49. request: The incoming request. Must contain an access_token.
  50. Returns:
  51. A transaction key
  52. """
  53. assert request.path is not None
  54. token = self.auth.get_access_token_from_request(request)
  55. return request.path.decode("utf8") + "/" + token
  56. def fetch_or_execute_request(
  57. self,
  58. request: Request,
  59. fn: Callable[P, Awaitable[Tuple[int, JsonDict]]],
  60. *args: P.args,
  61. **kwargs: P.kwargs,
  62. ) -> Awaitable[Tuple[int, JsonDict]]:
  63. """A helper function for fetch_or_execute which extracts
  64. a transaction key from the given request.
  65. See:
  66. fetch_or_execute
  67. """
  68. return self.fetch_or_execute(
  69. self._get_transaction_key(request), fn, *args, **kwargs
  70. )
  71. def fetch_or_execute(
  72. self,
  73. txn_key: str,
  74. fn: Callable[P, Awaitable[Tuple[int, JsonDict]]],
  75. *args: P.args,
  76. **kwargs: P.kwargs,
  77. ) -> "Deferred[Tuple[int, JsonDict]]":
  78. """Fetches the response for this transaction, or executes the given function
  79. to produce a response for this transaction.
  80. Args:
  81. txn_key: A key to ensure idempotency should fetch_or_execute be
  82. called again at a later point in time.
  83. fn: A function which returns a tuple of (response_code, response_dict).
  84. *args: Arguments to pass to fn.
  85. **kwargs: Keyword arguments to pass to fn.
  86. Returns:
  87. Deferred which resolves to a tuple of (response_code, response_dict).
  88. """
  89. if txn_key in self.transactions:
  90. observable = self.transactions[txn_key][0]
  91. else:
  92. # execute the function instead.
  93. deferred = run_in_background(fn, *args, **kwargs)
  94. observable = ObservableDeferred(deferred)
  95. self.transactions[txn_key] = (observable, self.clock.time_msec())
  96. # if the request fails with an exception, remove it
  97. # from the transaction map. This is done to ensure that we don't
  98. # cache transient errors like rate-limiting errors, etc.
  99. def remove_from_map(err: Failure) -> None:
  100. self.transactions.pop(txn_key, None)
  101. # we deliberately do not propagate the error any further, as we
  102. # expect the observers to have reported it.
  103. deferred.addErrback(remove_from_map)
  104. return make_deferred_yieldable(observable.observe())
  105. def _cleanup(self) -> None:
  106. now = self.clock.time_msec()
  107. for key in list(self.transactions):
  108. ts = self.transactions[key][1]
  109. if now > (ts + CLEANUP_PERIOD_MS): # after cleanup period
  110. del self.transactions[key]