m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
2.3 KiB

6 months ago
  1. from __future__ import absolute_import, division
  2. import copy
  3. import time
  4. class Heartbeat(object):
  5. DEFAULT_CONFIG = {
  6. 'group_id': None,
  7. 'heartbeat_interval_ms': 3000,
  8. 'session_timeout_ms': 10000,
  9. 'max_poll_interval_ms': 300000,
  10. 'retry_backoff_ms': 100,
  11. }
  12. def __init__(self, **configs):
  13. self.config = copy.copy(self.DEFAULT_CONFIG)
  14. for key in self.config:
  15. if key in configs:
  16. self.config[key] = configs[key]
  17. if self.config['group_id'] is not None:
  18. assert (self.config['heartbeat_interval_ms']
  19. <= self.config['session_timeout_ms']), (
  20. 'Heartbeat interval must be lower than the session timeout')
  21. self.last_send = -1 * float('inf')
  22. self.last_receive = -1 * float('inf')
  23. self.last_poll = -1 * float('inf')
  24. self.last_reset = time.time()
  25. self.heartbeat_failed = None
  26. def poll(self):
  27. self.last_poll = time.time()
  28. def sent_heartbeat(self):
  29. self.last_send = time.time()
  30. self.heartbeat_failed = False
  31. def fail_heartbeat(self):
  32. self.heartbeat_failed = True
  33. def received_heartbeat(self):
  34. self.last_receive = time.time()
  35. def time_to_next_heartbeat(self):
  36. """Returns seconds (float) remaining before next heartbeat should be sent"""
  37. time_since_last_heartbeat = time.time() - max(self.last_send, self.last_reset)
  38. if self.heartbeat_failed:
  39. delay_to_next_heartbeat = self.config['retry_backoff_ms'] / 1000
  40. else:
  41. delay_to_next_heartbeat = self.config['heartbeat_interval_ms'] / 1000
  42. return max(0, delay_to_next_heartbeat - time_since_last_heartbeat)
  43. def should_heartbeat(self):
  44. return self.time_to_next_heartbeat() == 0
  45. def session_timeout_expired(self):
  46. last_recv = max(self.last_receive, self.last_reset)
  47. return (time.time() - last_recv) > (self.config['session_timeout_ms'] / 1000)
  48. def reset_timeouts(self):
  49. self.last_reset = time.time()
  50. self.last_poll = time.time()
  51. self.heartbeat_failed = False
  52. def poll_timeout_expired(self):
  53. return (time.time() - self.last_poll) > (self.config['max_poll_interval_ms'] / 1000)