class Srvy::Result

Constants

EMPTY_RESULT_TTL

Public Class Methods

from_dns(dns_result) click to toggle source
# File lib/srvy/result.rb, line 5
def self.from_dns(dns_result)
  # for each SRV record
  srvs = dns_result.answer.select{|rr| rr.is_a?(Net::DNS::RR::SRV) }
  hosts = srvs.map do |srv|
    Srvy::Host.new(srv.host, srv.port, srv.weight, srv.priority, srv.ttl)
  end

  new(Time.now, hosts)
end
new(created_at, hosts) click to toggle source
# File lib/srvy/result.rb, line 15
def initialize(created_at, hosts)
  @created_at = created_at
  @hosts      = hosts
end

Public Instance Methods

expired?() click to toggle source
# File lib/srvy/result.rb, line 40
def expired?
  now = Time.now
  min_ttl = @hosts.map(&:ttl).min
  min_ttl ||= EMPTY_RESULT_TTL # in case there are no hosts
  @created_at + min_ttl < now
end
get_all() click to toggle source
# File lib/srvy/result.rb, line 36
def get_all
  @hosts
end
get_many() click to toggle source
# File lib/srvy/result.rb, line 32
def get_many
  best_priority_hosts_by_weight
end
get_single() click to toggle source
# File lib/srvy/result.rb, line 20
def get_single
  return nil if @hosts.empty?

  roll = rand(best_priority_cumulative_weight)
  acc = 0

  best_priority_hosts_by_weight.each do |host|
    acc += host.weight
    return host if roll < acc
  end
end

Private Instance Methods

best_priority() click to toggle source
# File lib/srvy/result.rb, line 57
def best_priority
  @best_priority ||= @hosts.map(&:priority).min
end
best_priority_cumulative_weight() click to toggle source
# File lib/srvy/result.rb, line 53
def best_priority_cumulative_weight
  best_priority_hosts_by_weight.map(&:weight).inject(0, :+)
end
best_priority_hosts_by_weight() click to toggle source
# File lib/srvy/result.rb, line 48
def best_priority_hosts_by_weight
  # sorted weight descending
  best_priority_hosts_by_weight ||= @hosts.select{|s| s.priority <= best_priority }.sort_by(&:weight).reverse
end