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.
 
 
 
 
 
 

204 lines
6.9 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 # type: ignore[union-attr] # Issue in Twisted's annotations
  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 # type: ignore[arg-type] # Issue in Twisted's type annotations
  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. Note that the function will be called with no logcontext, so if it is anything
  93. other than trivial, you probably want to wrap it in run_as_background_process.
  94. Args:
  95. f: The function to call repeatedly.
  96. msec: How long to wait between calls in milliseconds.
  97. *args: Postional arguments to pass to function.
  98. **kwargs: Key arguments to pass to function.
  99. """
  100. call = task.LoopingCall(f, *args, **kwargs)
  101. call.clock = self._reactor
  102. d = call.start(msec / 1000.0, now=False)
  103. d.addErrback(log_failure, "Looping call died", consumeErrors=False)
  104. return call
  105. def call_later(
  106. self, delay: float, callback: Callable, *args: Any, **kwargs: Any
  107. ) -> IDelayedCall:
  108. """Call something later
  109. Note that the function will be called with no logcontext, so if it is anything
  110. other than trivial, you probably want to wrap it in run_as_background_process.
  111. Args:
  112. delay: How long to wait in seconds.
  113. callback: Function to call
  114. *args: Postional arguments to pass to function.
  115. **kwargs: Key arguments to pass to function.
  116. """
  117. def wrapped_callback(*args: Any, **kwargs: Any) -> None:
  118. with context.PreserveLoggingContext():
  119. callback(*args, **kwargs)
  120. with context.PreserveLoggingContext():
  121. return self._reactor.callLater(delay, wrapped_callback, *args, **kwargs)
  122. def cancel_call_later(self, timer: IDelayedCall, ignore_errs: bool = False) -> None:
  123. try:
  124. timer.cancel()
  125. except Exception:
  126. if not ignore_errs:
  127. raise
  128. def log_failure(
  129. failure: Failure, msg: str, consumeErrors: bool = True
  130. ) -> Optional[Failure]:
  131. """Creates a function suitable for passing to `Deferred.addErrback` that
  132. logs any failures that occur.
  133. Args:
  134. failure: The Failure to log
  135. msg: Message to log
  136. consumeErrors: If true consumes the failure, otherwise passes on down
  137. the callback chain
  138. Returns:
  139. The Failure if consumeErrors is false. None, otherwise.
  140. """
  141. logger.error(
  142. msg, exc_info=(failure.type, failure.value, failure.getTracebackObject()) # type: ignore[arg-type]
  143. )
  144. if not consumeErrors:
  145. return failure
  146. return None
  147. # Version string with git info. Computed here once so that we don't invoke git multiple
  148. # times.
  149. SYNAPSE_VERSION = get_distribution_version_string("matrix-synapse", __file__)
  150. class ExceptionBundle(Exception):
  151. # A poor stand-in for something like Python 3.11's ExceptionGroup.
  152. # (A backport called `exceptiongroup` exists but seems overkill: we just want a
  153. # container type here.)
  154. def __init__(self, message: str, exceptions: Sequence[Exception]):
  155. parts = [message]
  156. for e in exceptions:
  157. parts.append(str(e))
  158. super().__init__("\n - ".join(parts))
  159. self.exceptions = exceptions