LatencyBuffer.rb 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. class LatencyBuffer
  2. class NotRequestedReturnLatencyError < StandardError; end
  3. def initialize
  4. @latencies = []
  5. @latencies_mutex = Mutex.new
  6. @packets = {}
  7. @packets_mutex = Mutex.new
  8. end
  9. def get_next_free_id
  10. rnd_id = Random.rand((1...(2**64)))
  11. id = rnd_id
  12. while @packets.key? id
  13. id += 1
  14. if id >= 2**64
  15. id = 1
  16. end
  17. end
  18. return id
  19. end
  20. def get_packet_id
  21. id = nil
  22. @packets_mutex.synchronize do
  23. id = get_next_free_id
  24. @packets[id] = Time.now
  25. end
  26. do_gc
  27. return id
  28. end
  29. def do_gc
  30. @packets_mutex.synchronize do
  31. @packets.delete_if do |id, time|
  32. (Time.now - time) > [2 * 60, get_latency].max
  33. end
  34. end
  35. end
  36. def receive_id_handler(id)
  37. time = nil
  38. @packets_mutex.synchronize do
  39. return unless @packets.key? id
  40. time = (Time.now - @packets[id]).to_f
  41. @packets.delete id
  42. end
  43. add_latency time
  44. end
  45. def add_latency(latency)
  46. @latencies_mutex.synchronize do
  47. @latencies << latency
  48. if @latencies.length > 12
  49. @latencies.shift
  50. end
  51. end
  52. end
  53. def get_latency
  54. return 1 if @latencies.length == 0
  55. @latencies_mutex.synchronize do
  56. latency = (@latencies.sum / @latencies.length).round(2)
  57. $logger.warn "Latency #{latency} is too low!" if latency < 1
  58. $logger.debug "Latency: #{latency}"
  59. return latency
  60. end
  61. end
  62. end