__init__.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  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. from synapse.api.errors import SynapseError
  16. from synapse.util.logcontext import PreserveLoggingContext
  17. from twisted.internet import defer, reactor, task
  18. import time
  19. import logging
  20. logger = logging.getLogger(__name__)
  21. def unwrapFirstError(failure):
  22. # defer.gatherResults and DeferredLists wrap failures.
  23. failure.trap(defer.FirstError)
  24. return failure.value.subFailure
  25. class Clock(object):
  26. """A small utility that obtains current time-of-day so that time may be
  27. mocked during unit-tests.
  28. TODO(paul): Also move the sleep() functionality into it
  29. """
  30. def time(self):
  31. """Returns the current system time in seconds since epoch."""
  32. return time.time()
  33. def time_msec(self):
  34. """Returns the current system time in miliseconds since epoch."""
  35. return int(self.time() * 1000)
  36. def looping_call(self, f, msec):
  37. """Call a function repeatedly.
  38. Waits `msec` initially before calling `f` for the first time.
  39. Args:
  40. f(function): The function to call repeatedly.
  41. msec(float): How long to wait between calls in milliseconds.
  42. """
  43. l = task.LoopingCall(f)
  44. l.start(msec / 1000.0, now=False)
  45. return l
  46. def call_later(self, delay, callback, *args, **kwargs):
  47. """Call something later
  48. Args:
  49. delay(float): How long to wait in seconds.
  50. callback(function): Function to call
  51. *args: Postional arguments to pass to function.
  52. **kwargs: Key arguments to pass to function.
  53. """
  54. def wrapped_callback(*args, **kwargs):
  55. with PreserveLoggingContext():
  56. callback(*args, **kwargs)
  57. with PreserveLoggingContext():
  58. return reactor.callLater(delay, wrapped_callback, *args, **kwargs)
  59. def cancel_call_later(self, timer, ignore_errs=False):
  60. try:
  61. timer.cancel()
  62. except:
  63. if not ignore_errs:
  64. raise
  65. def time_bound_deferred(self, given_deferred, time_out):
  66. if given_deferred.called:
  67. return given_deferred
  68. ret_deferred = defer.Deferred()
  69. def timed_out_fn():
  70. try:
  71. ret_deferred.errback(SynapseError(504, "Timed out"))
  72. except:
  73. pass
  74. try:
  75. given_deferred.cancel()
  76. except:
  77. pass
  78. timer = None
  79. def cancel(res):
  80. try:
  81. self.cancel_call_later(timer)
  82. except:
  83. pass
  84. return res
  85. ret_deferred.addBoth(cancel)
  86. def sucess(res):
  87. try:
  88. ret_deferred.callback(res)
  89. except:
  90. pass
  91. return res
  92. def err(res):
  93. try:
  94. ret_deferred.errback(res)
  95. except:
  96. pass
  97. given_deferred.addCallbacks(callback=sucess, errback=err)
  98. timer = self.call_later(time_out, timed_out_fn)
  99. return ret_deferred