25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

209 satır
7.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. import json
  15. import logging
  16. import typing
  17. from typing import Any, Callable, Dict, Generator, Optional, Sequence
  18. import attr
  19. from immutabledict import immutabledict
  20. from matrix_common.versionstring import get_distribution_version_string
  21. from typing_extensions import ParamSpec
  22. from twisted.internet import defer, task
  23. from twisted.internet.defer import Deferred
  24. from twisted.internet.interfaces import IDelayedCall, IReactorTime
  25. from twisted.internet.task import LoopingCall
  26. from twisted.python.failure import Failure
  27. from synapse.logging import context
  28. if typing.TYPE_CHECKING:
  29. pass
  30. logger = logging.getLogger(__name__)
  31. def _reject_invalid_json(val: Any) -> None:
  32. """Do not allow Infinity, -Infinity, or NaN values in JSON."""
  33. raise ValueError("Invalid JSON value: '%s'" % val)
  34. def _handle_immutabledict(obj: Any) -> Dict[Any, Any]:
  35. """Helper for json_encoder. Makes immutabledicts serializable by returning
  36. the underlying dict
  37. """
  38. if type(obj) is immutabledict:
  39. # fishing the protected dict out of the object is a bit nasty,
  40. # but we don't really want the overhead of copying the dict.
  41. try:
  42. # Safety: we catch the AttributeError immediately below.
  43. return obj._dict
  44. except AttributeError:
  45. # If all else fails, resort to making a copy of the immutabledict
  46. return dict(obj)
  47. raise TypeError(
  48. "Object of type %s is not JSON serializable" % obj.__class__.__name__
  49. )
  50. # A custom JSON encoder which:
  51. # * handles immutabledicts
  52. # * produces valid JSON (no NaNs etc)
  53. # * reduces redundant whitespace
  54. json_encoder = json.JSONEncoder(
  55. allow_nan=False, separators=(",", ":"), default=_handle_immutabledict
  56. )
  57. # Create a custom decoder to reject Python extensions to JSON.
  58. json_decoder = json.JSONDecoder(parse_constant=_reject_invalid_json)
  59. def unwrapFirstError(failure: Failure) -> Failure:
  60. # Deprecated: you probably just want to catch defer.FirstError and reraise
  61. # the subFailure's value, which will do a better job of preserving stacktraces.
  62. # (actually, you probably want to use yieldable_gather_results anyway)
  63. failure.trap(defer.FirstError)
  64. return failure.value.subFailure
  65. P = ParamSpec("P")
  66. @attr.s(slots=True)
  67. class Clock:
  68. """
  69. A Clock wraps a Twisted reactor and provides utilities on top of it.
  70. Args:
  71. reactor: The Twisted reactor to use.
  72. """
  73. _reactor: IReactorTime = attr.ib()
  74. @defer.inlineCallbacks
  75. def sleep(self, seconds: float) -> "Generator[Deferred[float], Any, Any]":
  76. d: defer.Deferred[float] = defer.Deferred()
  77. with context.PreserveLoggingContext():
  78. self._reactor.callLater(seconds, d.callback, seconds)
  79. res = yield d
  80. return res
  81. def time(self) -> float:
  82. """Returns the current system time in seconds since epoch."""
  83. return self._reactor.seconds()
  84. def time_msec(self) -> int:
  85. """Returns the current system time in milliseconds since epoch."""
  86. return int(self.time() * 1000)
  87. def looping_call(
  88. self, f: Callable[P, object], msec: float, *args: P.args, **kwargs: P.kwargs
  89. ) -> LoopingCall:
  90. """Call a function repeatedly.
  91. Waits `msec` initially before calling `f` for the first time.
  92. If the function given to `looping_call` returns an awaitable/deferred, the next
  93. call isn't scheduled until after the returned awaitable has finished. We get
  94. this functionality thanks to this function being a thin wrapper around
  95. `twisted.internet.task.LoopingCall`.
  96. Note that the function will be called with no logcontext, so if it is anything
  97. other than trivial, you probably want to wrap it in run_as_background_process.
  98. Args:
  99. f: The function to call repeatedly.
  100. msec: How long to wait between calls in milliseconds.
  101. *args: Postional arguments to pass to function.
  102. **kwargs: Key arguments to pass to function.
  103. """
  104. call = task.LoopingCall(f, *args, **kwargs)
  105. call.clock = self._reactor
  106. d = call.start(msec / 1000.0, now=False)
  107. d.addErrback(log_failure, "Looping call died", consumeErrors=False)
  108. return call
  109. def call_later(
  110. self, delay: float, callback: Callable, *args: Any, **kwargs: Any
  111. ) -> IDelayedCall:
  112. """Call something later
  113. Note that the function will be called with no logcontext, so if it is anything
  114. other than trivial, you probably want to wrap it in run_as_background_process.
  115. Args:
  116. delay: How long to wait in seconds.
  117. callback: Function to call
  118. *args: Postional arguments to pass to function.
  119. **kwargs: Key arguments to pass to function.
  120. """
  121. def wrapped_callback(*args: Any, **kwargs: Any) -> None:
  122. with context.PreserveLoggingContext():
  123. callback(*args, **kwargs)
  124. with context.PreserveLoggingContext():
  125. return self._reactor.callLater(delay, wrapped_callback, *args, **kwargs)
  126. def cancel_call_later(self, timer: IDelayedCall, ignore_errs: bool = False) -> None:
  127. try:
  128. timer.cancel()
  129. except Exception:
  130. if not ignore_errs:
  131. raise
  132. def log_failure(
  133. failure: Failure, msg: str, consumeErrors: bool = True
  134. ) -> Optional[Failure]:
  135. """Creates a function suitable for passing to `Deferred.addErrback` that
  136. logs any failures that occur.
  137. Args:
  138. failure: The Failure to log
  139. msg: Message to log
  140. consumeErrors: If true consumes the failure, otherwise passes on down
  141. the callback chain
  142. Returns:
  143. The Failure if consumeErrors is false. None, otherwise.
  144. """
  145. logger.error(
  146. msg, exc_info=(failure.type, failure.value, failure.getTracebackObject())
  147. )
  148. if not consumeErrors:
  149. return failure
  150. return None
  151. # Version string with git info. Computed here once so that we don't invoke git multiple
  152. # times.
  153. SYNAPSE_VERSION = get_distribution_version_string("matrix-synapse", __file__)
  154. class ExceptionBundle(Exception):
  155. # A poor stand-in for something like Python 3.11's ExceptionGroup.
  156. # (A backport called `exceptiongroup` exists but seems overkill: we just want a
  157. # container type here.)
  158. def __init__(self, message: str, exceptions: Sequence[Exception]):
  159. parts = [message]
  160. for e in exceptions:
  161. parts.append(str(e))
  162. super().__init__("\n - ".join(parts))
  163. self.exceptions = exceptions