__init__.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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
  18. import attr
  19. from frozendict import frozendict
  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_frozendict(obj: Any) -> Dict[Any, Any]:
  35. """Helper for json_encoder. Makes frozendicts serializable by returning
  36. the underlying dict
  37. """
  38. if type(obj) is frozendict:
  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. # See https://github.com/matrix-org/python-canonicaljson/issues/36#issuecomment-927816293
  44. # for discussion on how frozendict's internals have changed over time.
  45. return obj._dict # type: ignore[attr-defined]
  46. except AttributeError:
  47. # When the C implementation of frozendict is used,
  48. # there isn't a `_dict` attribute with a dict
  49. # so we resort to making a copy of the frozendict
  50. return dict(obj)
  51. raise TypeError(
  52. "Object of type %s is not JSON serializable" % obj.__class__.__name__
  53. )
  54. # A custom JSON encoder which:
  55. # * handles frozendicts
  56. # * produces valid JSON (no NaNs etc)
  57. # * reduces redundant whitespace
  58. json_encoder = json.JSONEncoder(
  59. allow_nan=False, separators=(",", ":"), default=_handle_frozendict
  60. )
  61. # Create a custom decoder to reject Python extensions to JSON.
  62. json_decoder = json.JSONDecoder(parse_constant=_reject_invalid_json)
  63. def unwrapFirstError(failure: Failure) -> Failure:
  64. # Deprecated: you probably just want to catch defer.FirstError and reraise
  65. # the subFailure's value, which will do a better job of preserving stacktraces.
  66. # (actually, you probably want to use yieldable_gather_results anyway)
  67. failure.trap(defer.FirstError)
  68. return failure.value.subFailure # type: ignore[union-attr] # Issue in Twisted's annotations
  69. P = ParamSpec("P")
  70. @attr.s(slots=True)
  71. class Clock:
  72. """
  73. A Clock wraps a Twisted reactor and provides utilities on top of it.
  74. Args:
  75. reactor: The Twisted reactor to use.
  76. """
  77. _reactor: IReactorTime = attr.ib()
  78. @defer.inlineCallbacks # type: ignore[arg-type] # Issue in Twisted's type annotations
  79. def sleep(self, seconds: float) -> "Generator[Deferred[float], Any, Any]":
  80. d: defer.Deferred[float] = defer.Deferred()
  81. with context.PreserveLoggingContext():
  82. self._reactor.callLater(seconds, d.callback, seconds)
  83. res = yield d
  84. return res
  85. def time(self) -> float:
  86. """Returns the current system time in seconds since epoch."""
  87. return self._reactor.seconds()
  88. def time_msec(self) -> int:
  89. """Returns the current system time in milliseconds since epoch."""
  90. return int(self.time() * 1000)
  91. def looping_call(
  92. self, f: Callable[P, object], msec: float, *args: P.args, **kwargs: P.kwargs
  93. ) -> LoopingCall:
  94. """Call a function repeatedly.
  95. Waits `msec` initially before calling `f` for the first time.
  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()) # type: ignore[arg-type]
  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__)