25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

108 lines
3.4 KiB

  1. # Copyright 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 logging
  15. from typing import Generic, Hashable, List, Set, TypeVar
  16. import attr
  17. logger = logging.getLogger(__name__)
  18. T = TypeVar("T", bound=Hashable)
  19. @attr.s(slots=True, frozen=True, auto_attribs=True)
  20. class _Entry(Generic[T]):
  21. end_key: int
  22. elements: Set[T] = attr.Factory(set)
  23. class WheelTimer(Generic[T]):
  24. """Stores arbitrary objects that will be returned after their timers have
  25. expired.
  26. """
  27. def __init__(self, bucket_size: int = 5000) -> None:
  28. """
  29. Args:
  30. bucket_size: Size of buckets in ms. Corresponds roughly to the
  31. accuracy of the timer.
  32. """
  33. self.bucket_size: int = bucket_size
  34. self.entries: List[_Entry[T]] = []
  35. self.current_tick: int = 0
  36. def insert(self, now: int, obj: T, then: int) -> None:
  37. """Inserts object into timer.
  38. Args:
  39. now: Current time in msec
  40. obj: Object to be inserted
  41. then: When to return the object strictly after.
  42. """
  43. then_key = int(then / self.bucket_size) + 1
  44. now_key = int(now / self.bucket_size)
  45. if self.entries:
  46. min_key = self.entries[0].end_key
  47. max_key = self.entries[-1].end_key
  48. if min_key < now_key - 10:
  49. # If we have ten buckets that are due and still nothing has
  50. # called `fetch()` then we likely have a bug that is causing a
  51. # memory leak.
  52. logger.warning(
  53. "Inserting into a wheel timer that hasn't been read from recently. Item: %s",
  54. obj,
  55. )
  56. if then_key <= max_key:
  57. # The max here is to protect against inserts for times in the past
  58. self.entries[max(min_key, then_key) - min_key].elements.add(obj)
  59. return
  60. next_key = now_key + 1
  61. if self.entries:
  62. last_key = self.entries[-1].end_key
  63. else:
  64. last_key = next_key
  65. # Handle the case when `then` is in the past and `entries` is empty.
  66. then_key = max(last_key, then_key)
  67. # Add empty entries between the end of the current list and when we want
  68. # to insert. This ensures there are no gaps.
  69. self.entries.extend(_Entry(key) for key in range(last_key, then_key + 1))
  70. self.entries[-1].elements.add(obj)
  71. def fetch(self, now: int) -> List[T]:
  72. """Fetch any objects that have timed out
  73. Args:
  74. now: Current time in msec
  75. Returns:
  76. List of objects that have timed out
  77. """
  78. now_key = int(now / self.bucket_size)
  79. ret: List[T] = []
  80. while self.entries and self.entries[0].end_key <= now_key:
  81. ret.extend(self.entries.pop(0).elements)
  82. return ret
  83. def __len__(self) -> int:
  84. return sum(len(entry.elements) for entry in self.entries)