0
0
Fork 0
mirror of https://github.com/discourse/discourse.git synced 2026-08-11 02:59:07 +08:00
discourse/plugins/discourse-ai/lib/utils/dns_srv.rb
Rafael dos Santos Silva 5ba7d279f9
FEATURE: Use GET /health for DNS SRV availability checks (#36300)
Changes AI server availability check from HEAD / to GET /health for more
reliable health status verification.

The previous implementation used HEAD / which only verified the server
was reachable, but didn't validate its actual health status. Now uses
GET /health and checks response.success? for proper health validation.
2025-11-27 16:22:36 -03:00

65 lines
1.6 KiB
Ruby
Vendored

# frozen_string_literal: true
require "resolv"
module DiscourseAi
module Utils
module DnsSrv
def self.lookup(domain)
Discourse
.cache
.fetch("dns_srv_lookup:#{domain}", expires_in: 5.minutes) do
resources = dns_srv_lookup_for_domain(domain)
server_election(resources)
end
end
private
def self.dns_srv_lookup_for_domain(domain)
resolver = Resolv::DNS.new
resolver.getresources(domain, Resolv::DNS::Resource::IN::SRV)
end
def self.select_server(resources)
priority = resources.group_by(&:priority).keys.min
priority_resources = resources.select { |r| r.priority == priority }
total_weight = priority_resources.map(&:weight).sum
random_weight = rand(total_weight)
priority_resources.each do |resource|
random_weight -= resource.weight
return resource if random_weight < 0
end
end
def self.server_available?(server)
begin
conn = Faraday.new { |f| f.adapter FinalDestination::FaradayAdapter }
response = conn.get("https://#{server.target}:#{server.port}/health")
response.success?
rescue StandardError
false
end
end
def self.server_election(resources)
return nil if resources.empty?
return resources.first if resources.length == 1
candidate = select_server(resources)
if server_available?(candidate)
candidate
else
server_election(resources - [candidate])
end
end
end
end
end