__init__.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014, 2015 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.util.logcontext import LoggingContext
  16. from twisted.internet import defer, reactor, task
  17. import time
  18. import logging
  19. logger = logging.getLogger(__name__)
  20. class Clock(object):
  21. """A small utility that obtains current time-of-day so that time may be
  22. mocked during unit-tests.
  23. TODO(paul): Also move the sleep() functionallity into it
  24. """
  25. def time(self):
  26. """Returns the current system time in seconds since epoch."""
  27. return time.time()
  28. def time_msec(self):
  29. """Returns the current system time in miliseconds since epoch."""
  30. return self.time() * 1000
  31. def looping_call(self, f, msec):
  32. l = task.LoopingCall(f)
  33. l.start(msec/1000.0, now=False)
  34. return l
  35. def stop_looping_call(self, loop):
  36. loop.stop()
  37. def call_later(self, delay, callback):
  38. current_context = LoggingContext.current_context()
  39. def wrapped_callback():
  40. LoggingContext.thread_local.current_context = current_context
  41. callback()
  42. return reactor.callLater(delay, wrapped_callback)
  43. def cancel_call_later(self, timer):
  44. timer.cancel()
  45. def time_bound_deferred(self, given_deferred, time_out):
  46. if given_deferred.called:
  47. return given_deferred
  48. ret_deferred = defer.Deferred()
  49. def timed_out_fn():
  50. try:
  51. ret_deferred.errback(RuntimeError("Timed out"))
  52. except:
  53. pass
  54. try:
  55. given_deferred.cancel()
  56. except:
  57. pass
  58. timer = None
  59. def cancel(res):
  60. try:
  61. self.cancel_call_later(timer)
  62. except:
  63. pass
  64. return res
  65. ret_deferred.addBoth(cancel)
  66. def sucess(res):
  67. try:
  68. ret_deferred.callback(res)
  69. except:
  70. pass
  71. return res
  72. def err(res):
  73. try:
  74. ret_deferred.errback(res)
  75. except:
  76. pass
  77. given_deferred.addCallbacks(callback=sucess, errback=err)
  78. timer = self.call_later(time_out, timed_out_fn)
  79. return ret_deferred