persistence.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 all the persistence actions done by the federation
  16. package.
  17. These actions are mostly only used by the :py:mod:`.replication` module.
  18. """
  19. import logging
  20. from typing import Optional, Tuple
  21. from synapse.federation.units import Transaction
  22. from synapse.logging.utils import log_function
  23. from synapse.types import JsonDict
  24. logger = logging.getLogger(__name__)
  25. class TransactionActions:
  26. """Defines persistence actions that relate to handling Transactions."""
  27. def __init__(self, datastore):
  28. self.store = datastore
  29. @log_function
  30. async def have_responded(
  31. self, origin: str, transaction: Transaction
  32. ) -> Optional[Tuple[int, JsonDict]]:
  33. """Have we already responded to a transaction with the same id and
  34. origin?
  35. Returns:
  36. `None` if we have not previously responded to this transaction or a
  37. 2-tuple of `(int, dict)` representing the response code and response body.
  38. """
  39. transaction_id = transaction.transaction_id # type: ignore
  40. if not transaction_id:
  41. raise RuntimeError("Cannot persist a transaction with no transaction_id")
  42. return await self.store.get_received_txn_response(transaction_id, origin)
  43. @log_function
  44. async def set_response(
  45. self, origin: str, transaction: Transaction, code: int, response: JsonDict
  46. ) -> None:
  47. """Persist how we responded to a transaction."""
  48. transaction_id = transaction.transaction_id # type: ignore
  49. if not transaction_id:
  50. raise RuntimeError("Cannot persist a transaction with no transaction_id")
  51. await self.store.set_received_txn_response(
  52. transaction_id, origin, code, response
  53. )