__init__.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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. import logging
  16. from itertools import islice
  17. import attr
  18. from twisted.internet import defer, task
  19. from synapse.util.logcontext import PreserveLoggingContext
  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. @attr.s
  26. class Clock(object):
  27. """
  28. A Clock wraps a Twisted reactor and provides utilities on top of it.
  29. Args:
  30. reactor: The Twisted reactor to use.
  31. """
  32. _reactor = attr.ib()
  33. @defer.inlineCallbacks
  34. def sleep(self, seconds):
  35. d = defer.Deferred()
  36. with PreserveLoggingContext():
  37. self._reactor.callLater(seconds, d.callback, seconds)
  38. res = yield d
  39. defer.returnValue(res)
  40. def time(self):
  41. """Returns the current system time in seconds since epoch."""
  42. return self._reactor.seconds()
  43. def time_msec(self):
  44. """Returns the current system time in miliseconds since epoch."""
  45. return int(self.time() * 1000)
  46. def looping_call(self, f, msec):
  47. """Call a function repeatedly.
  48. Waits `msec` initially before calling `f` for the first time.
  49. Args:
  50. f(function): The function to call repeatedly.
  51. msec(float): How long to wait between calls in milliseconds.
  52. """
  53. call = task.LoopingCall(f)
  54. call.clock = self._reactor
  55. call.start(msec / 1000.0, now=False)
  56. return call
  57. def call_later(self, delay, callback, *args, **kwargs):
  58. """Call something later
  59. Args:
  60. delay(float): How long to wait in seconds.
  61. callback(function): Function to call
  62. *args: Postional arguments to pass to function.
  63. **kwargs: Key arguments to pass to function.
  64. """
  65. def wrapped_callback(*args, **kwargs):
  66. with PreserveLoggingContext():
  67. callback(*args, **kwargs)
  68. with PreserveLoggingContext():
  69. return self._reactor.callLater(delay, wrapped_callback, *args, **kwargs)
  70. def cancel_call_later(self, timer, ignore_errs=False):
  71. try:
  72. timer.cancel()
  73. except Exception:
  74. if not ignore_errs:
  75. raise
  76. def batch_iter(iterable, size):
  77. """batch an iterable up into tuples with a maximum size
  78. Args:
  79. iterable (iterable): the iterable to slice
  80. size (int): the maximum batch size
  81. Returns:
  82. an iterator over the chunks
  83. """
  84. # make sure we can deal with iterables like lists too
  85. sourceiter = iter(iterable)
  86. # call islice until it returns an empty tuple
  87. return iter(lambda: tuple(islice(sourceiter, size)), ())