discourse-ai/lib/utils/dns_srv.rb
Sam 117c06220e
FEATURE: allow artifacts to be updated (#980)
Add support for versioned artifacts with improved diff handling

* Add versioned artifacts support allowing artifacts to be updated and tracked
  - New `ai_artifact_versions` table to store version history
  - Support for updating artifacts through a new `UpdateArtifact` tool
  - Add version-aware artifact rendering in posts
  - Include change descriptions for version tracking

* Enhance artifact rendering and security
  - Add support for module-type scripts and external JS dependencies
  - Expand CSP to allow trusted CDN sources (unpkg, cdnjs, jsdelivr, googleapis)
  - Improve JavaScript handling in artifacts

* Implement robust diff handling system (this is dormant but ready to use once LLMs catch up)
  - Add new DiffUtils module for applying changes to artifacts
  - Support for unified diff format with multiple hunks
  - Intelligent handling of whitespace and line endings
  - Comprehensive error handling for diff operations

* Update routes and UI components
  - Add versioned artifact routes
  - Update markdown processing for versioned artifacts

Also

- Tweaks summary prompt
- Improves upload support in custom tool to also provide urls
2024-12-03 07:23:31 +11:00

66 lines
1.6 KiB
Ruby

# 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 }
conn.head("https://#{server.target}:#{server.port}")
true
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