123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- class LatencyBuffer
- class NotRequestedReturnLatencyError < StandardError; end
- def initialize
- @latencies = []
- @latencies_mutex = Mutex.new
- @packets = {}
- @packets_mutex = Mutex.new
- end
- def get_next_free_id
- rnd_id = Random.rand((1...(2**64)))
- id = rnd_id
- while @packets.key? id
- id += 1
- if id >= 2**64
- id = 1
- end
- end
- return id
- end
- def get_packet_id
- id = nil
- @packets_mutex.synchronize do
- id = get_next_free_id
- @packets[id] = Time.now
- end
- do_gc
- return id
- end
- def do_gc
- @packets_mutex.synchronize do
- @packets.delete_if do |id, time|
- (Time.now - time) > [2 * 60, get_latency].max
- end
- end
- end
- def receive_id_handler(id)
- time = nil
- @packets_mutex.synchronize do
- return unless @packets.key? id
- time = (Time.now - @packets[id]).to_f
- @packets.delete id
- end
- add_latency time
- end
- def add_latency(latency)
- @latencies_mutex.synchronize do
- @latencies << latency
- if @latencies.length > 12
- @latencies.shift
- end
- end
- end
- def get_latency
- return 1 if @latencies.length == 0
- @latencies_mutex.synchronize do
- latency = (@latencies.sum / @latencies.length).round(2)
- $logger.warn "Latency #{latency} is too low!" if latency < 1
- $logger.debug "Latency: #{latency}"
- return latency
- end
- end
- end
|