Skip to content
Merged
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
- **Behavior change:** a successful failover during ActiveRecord's connection check (`active?`) no longer raises `FailoverSuccessError`: no statement of the application's was in flight, so the adapter reconnects silently, as ActiveRecord does for a dead connection, and the next statement runs on the new writer. `TransactionStateUnknownError` is still raised when an ActiveRecord transaction was open, because that transaction was lost; otherwise `active?` returns `false`. A failover during `reset!` completes the reset on the new writer instead of raising. `active?` returns `false`, and `reset!` raises `ActiveRecord::ConnectionFailed`, when failover fails. `aws_mysql2` and `aws_trilogy` are unchanged by these `active?`/`reset!` changes.
- Hardened every ActiveRecord adapter (`aws_postgresql`, `aws_mysql2`, `aws_trilogy`) against any other code path that touches the raw connection outside `with_raw_connection` after a failover. The wrapper's `Method invoked against old connection` error is now flagged `needs_reconfiguration`, so the adapter's exception translation clears ActiveRecord's prepared statement cache and re-applies the connection's settings on the first such failure, instead of every statement prepared before the failover failing until the connection is discarded.
- **Behavior change:** that error is still an `AwsError` with the same message, but `needs_reconfiguration` is now `true` (`connection_broken` stays `false`). Code that inspects `needs_reconfiguration` on wrapper errors will now see it set.
- Fixed failover retrying instance hosts that can't be resolved until `failover_timeout_sec` (default 300 s) when the connection host isn't a recognized RDS endpoint (an IP address or your own domain name) and `cluster_instance_host_pattern` isn't set. With `failover` or `gdb_failover` loaded (`failover` is in the default plugin list) on an Aurora or RDS Multi-AZ DB cluster, the wrapper now logs a warning when the first connection to such a host opens, and failover raises `FailoverFailedError` immediately, with a message that names `cluster_instance_host_pattern`. For `gdb_failover` on a database identified as a regional cluster rather than a Global Database (for example with `wrapper_dialect: aurora-pg`), the message explains that `global_cluster_instance_host_patterns` doesn't apply. A future major version will raise an error at connect for this configuration ([PR #235](https://github.com/aws/aws-advanced-ruby-driver-wrapper/pull/235), [documentation](https://aws.github.io/aws-advanced-wrapper-docs/ruby/enhanced-failover#host-pattern)).
- **Behavior change:** if bare instance identifiers resolve in your environment (for example through a DNS search domain), failover used to succeed in this configuration and now fails immediately. Set `cluster_instance_host_pattern: "?"` to keep the previous behavior.

## [1.1.0] - 2026-11-05

Expand Down
1 change: 1 addition & 0 deletions lib/aws_advanced_ruby_driver_wrapper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ def self.clear_caches
Utils::RdsUtils.clear_cache
Services::DialectService.known_endpoint_dialects.clear
Services::HostService.clear_id_cache
Plugins::FailoverPlugin::MISSING_PATTERN_WARNED_HOSTS.clear if defined?(Plugins::FailoverPlugin)
end

# Runs in a forked child (see ForkHook). Only the forking thread survives a fork, so every background
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,12 @@ def force_refresh(verify_writer, timeout_sec)
nil
end

# Instance hosts come from the region templates in global_cluster_instance_host_patterns, which is
# required, so they never depend on the bare instance template built for a non-RDS connection host.
def instance_host_pattern_missing?
false
end

private

def build_instance_templates_by_region
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ def initialize(service_container:, topology_utils:)
props = @service_container.connection_service.wrapper_props
@cluster_id = PropertyDefinition::CLUSTER_ID.get_string(props)
@instance_template = build_instance_template(props)
@instance_host_pattern_missing = PropertyDefinition::CLUSTER_INSTANCE_HOST_PATTERN.get(props).nil? &&
@instance_template.host == Utils::RdsUtils::BARE_INSTANCE_HOST_PATTERN
validate_host_pattern!(@instance_template.host)
@rds_url_type = Utils::RdsUtils.identify_rds_type(initial_host_info.host)

Expand Down Expand Up @@ -107,6 +109,17 @@ def stop_monitor
@service_container.monitor_service.stop_and_remove(:cluster_topology, @cluster_id)
end

# Whether DB instance hosts can't be derived from the topology. This is the case when the connection
# host isn't a recognized RDS endpoint and cluster_instance_host_pattern isn't set: the instance template
# is then a bare '?', so instance hosts are bare instance identifiers that usually don't resolve. An
# explicitly set '?' pattern doesn't count: it is how users whose environment resolves bare instance
# identifiers (e.g. through a DNS search domain) opt out of the warning and of failing over immediately.
#
# @return [Boolean]
def instance_host_pattern_missing?
@instance_host_pattern_missing
end

private

def stored_topology
Expand Down
130 changes: 108 additions & 22 deletions lib/aws_advanced_ruby_driver_wrapper/plugins/failover_plugin.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@ class FailoverPlugin
TELEMETRY_WRITER_FAILOVER = 'failover to writer host'
TELEMETRY_READER_FAILOVER = 'failover to replica'

PLUGIN_CODE = 'failover'

# Connection hosts already warned about a missing cluster_instance_host_pattern, so that the warning is
# logged once per host rather than once per connection.
MISSING_PATTERN_WARNED_HOSTS = Concurrent::Set.new

def initialize(service_container, props = ::Concurrent::Map.new)
@service_container = service_container
@wrapper_props = props
Expand All @@ -65,28 +71,9 @@ def initialize(service_container, props = ::Concurrent::Map.new)

def connect(host_info, driver_props, is_initial_connection, pipeline_callable)
init_failover_mode

unless PropertyDefinition::ENABLE_CONNECT_FAILOVER.get_bool(@wrapper_props)
return verified_connection(is_initial_connection, host_info, driver_props, pipeline_callable)
end

topology_host = host_service.hosts.find { |h| h.host_and_port == host_info&.host_and_port }

if !topology_host.nil? && topology_host.availability == Host::HostAvailability::UNAVAILABLE
host_service.refresh_host_list
return connect_via_failover(is_initial_connection)
end

begin
conn = verified_connection(is_initial_connection, host_info, driver_props, pipeline_callable)
host_service.refresh_host_list if is_initial_connection
conn
rescue StandardError => e
raise unless trigger_failover?(e)

host_service.set_availability(host_info, Host::HostAvailability::UNAVAILABLE)
connect_via_failover(is_initial_connection)
end
conn = connect_with_failover(host_info, driver_props, is_initial_connection, pipeline_callable)
warn_if_instance_host_pattern_missing if is_initial_connection
conn
end

def execute(method_name, pipeline_callable, *, **, &)
Expand Down Expand Up @@ -117,6 +104,103 @@ def execute(method_name, pipeline_callable, *, **, &)

private

def connect_with_failover(host_info, driver_props, is_initial_connection, pipeline_callable)
unless PropertyDefinition::ENABLE_CONNECT_FAILOVER.get_bool(@wrapper_props)
return verified_connection(is_initial_connection, host_info, driver_props, pipeline_callable)
end

topology_host = host_service.hosts.find { |h| h.host_and_port == host_info&.host_and_port }

if !topology_host.nil? && topology_host.availability == Host::HostAvailability::UNAVAILABLE
host_service.refresh_host_list
return connect_via_failover(is_initial_connection)
end

begin
conn = verified_connection(is_initial_connection, host_info, driver_props, pipeline_callable)
host_service.refresh_host_list if is_initial_connection
conn
rescue StandardError => e
raise unless trigger_failover?(e)

host_service.set_availability(host_info, Host::HostAvailability::UNAVAILABLE)
connect_via_failover(is_initial_connection)
end
end

# Failover needs DB instance hosts it can resolve. Whether it has them is only known once the initial
# connection has settled the dialect: cluster dialects (Aurora, RDS Multi-AZ DB cluster) then use an
# RdsHostListProvider, which reports whether the instance host pattern is missing. A single instance or a
# community database never has one, so it isn't affected. A missing pattern is logged as a warning, once
# per host, and the connection is still returned; failover then fails immediately (see
# #raise_if_instance_host_pattern_missing).
def warn_if_instance_host_pattern_missing
return unless instance_host_pattern_missing?

host = connection_service.initial_host_info&.host
return unless MISSING_PATTERN_WARNED_HOSTS.add?(host)

logger.warn("#{missing_instance_host_pattern_problem(host)}. Failover will fail with FailoverFailedError. " \
"#{missing_instance_host_pattern_fix}")
end

# Failover can't reach any DB instance when the instance host pattern is missing, since the instance hosts
# are bare instance identifiers. Failing right away, with the same explanation as the warning logged at
# connect, is better than retrying them until failover_timeout_sec.
#
# @raise [Errors::FailoverFailedError] if the instance host pattern is missing
def raise_if_instance_host_pattern_missing
return unless instance_host_pattern_missing?

host = connection_service.initial_host_info&.host
raise Errors::FailoverFailedError,
"Failover is not possible. #{missing_instance_host_pattern_problem(host)}. #{missing_instance_host_pattern_fix}"
end

def instance_host_pattern_missing?
provider = host_service.host_list_provider
provider.respond_to?(:instance_host_pattern_missing?) && provider.instance_host_pattern_missing?
end

# @return [Boolean] whether wrapper_plugins was set by the user. This plugin is loaded, so it is in the list.
def plugin_requested_explicitly?
@wrapper_props.key?(PropertyDefinition::PLUGINS.name)
end

# The warning logged at connect and the error raised by failover are both built from the methods below, so
# they describe the problem and its fix the same way.

# @return [String] a clause, without trailing punctuation, saying why the instance hosts can't be built
def missing_instance_host_pattern_reason(host)
"The connection host '#{host}' is not a recognized RDS endpoint and " \
"#{PropertyDefinition::CLUSTER_INSTANCE_HOST_PATTERN.name} is not set"
end

# @return [String] what to set cluster_instance_host_pattern to, phrased to follow "Set" or "set"
def instance_host_pattern_setting
"#{PropertyDefinition::CLUSTER_INSTANCE_HOST_PATTERN.name} to a DNS pattern that resolves to the cluster's " \
"instances (for example, '?.XXX.us-east-1.rds.amazonaws.com', or '?' if bare instance identifiers " \
'resolve in your environment)'
end

# @return [String] a clause, without trailing punctuation, describing the problem
def missing_instance_host_pattern_problem(host)
"#{missing_instance_host_pattern_reason(host)}, so the #{self.class::PLUGIN_CODE} plugin cannot build " \
'DB instance hosts from the cluster topology'
end

# @return [String] the fixes, as one or more full sentences
def missing_instance_host_pattern_fix
plugin_code = self.class::PLUGIN_CODE
remedy = if plugin_requested_explicitly?
"remove #{plugin_code} from #{PropertyDefinition::PLUGINS.name}"
else
"set #{PropertyDefinition::PLUGINS.name} to a list without #{plugin_code} (it is enabled by default)"
end

"Set #{instance_host_pattern_setting}, or #{remedy}."
end

def connect_via_failover(is_initial_connection)
begin
failover
Expand Down Expand Up @@ -310,6 +394,7 @@ def failover_reader
failover_deadline = failover_start + @failover_timeout

logger.info { 'Starting reader failover' }
raise_if_instance_host_pattern_missing

unless host_service.force_refresh_host_list?(verify_writer: false, timeout_sec: 0)
raise Errors::FailoverFailedError, 'The request to discover the new topology was unsuccessful'
Expand Down Expand Up @@ -337,6 +422,7 @@ def failover_writer
result = nil

logger.info { 'Starting writer failover' }
raise_if_instance_host_pattern_missing

begin
unless host_service.force_refresh_host_list?(verify_writer: true, timeout_sec: @failover_timeout)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
# limitations under the License.

require_relative '../failover_plugin'
require_relative '../../db_dialects/dialect_codes'
require_relative '../../errors'
require_relative '../../host/host_role'
require_relative '../../property_definition'
Expand All @@ -39,6 +40,7 @@ module Gdb
# regions are never selected.
class GdbFailoverPlugin < FailoverPlugin
TELEMETRY_FAILOVER = 'global database failover'
PLUGIN_CODE = 'gdb_failover'

def initialize(service_container, props = ::Concurrent::Map.new)
super
Expand Down Expand Up @@ -216,6 +218,7 @@ def failover_with_plan
def failover_plan
# This is expected to return once the topology has stabilized, i.e. once the cluster
# control plane has already chosen a new writer.
raise_if_instance_host_pattern_missing
unless host_service.force_refresh_host_list?(verify_writer: true, timeout_sec: @failover_timeout)
raise Errors::FailoverFailedError, 'The request to discover the new topology timed out or was unsuccessful'
end
Expand Down Expand Up @@ -418,6 +421,27 @@ def failover_reader
def failover_writer
raise NotImplementedError, "#{self.class} performs failover via #failover"
end

# The instance host pattern can only be missing when the database was identified as a regional cluster:
# for a Global Database, instance hosts come from global_cluster_instance_host_patterns, which is
# required. On a regional cluster that setting is not read, so the problem and fix explain how to have
# the database treated as a Global Database, or how to configure the regional cluster instead.
def missing_instance_host_pattern_problem(host)
"#{missing_instance_host_pattern_reason(host)}. The database was identified as a regional cluster rather " \
"than an Aurora Global Database, so #{PropertyDefinition::GLOBAL_CLUSTER_INSTANCE_HOST_PATTERNS.name} " \
"does not apply and the #{PLUGIN_CODE} plugin cannot build DB instance hosts from the cluster topology"
end

def missing_instance_host_pattern_fix
"If the cluster is a member of a Global Database, set #{PropertyDefinition::DIALECT.name} to " \
"'#{global_dialect_code}' (without it, a Global Database is only detected when it spans more than one " \
"region) and set #{PropertyDefinition::GLOBAL_CLUSTER_INSTANCE_HOST_PATTERNS.name}. For a standalone " \
"cluster, use the failover plugin instead, and set #{instance_host_pattern_setting}."
end

def global_dialect_code
driver_dialect.database_engine == :mysql ? DialectCodes::GLOBAL_AURORA_MYSQL : DialectCodes::GLOBAL_AURORA_PG
end
end
end
end
Expand Down
8 changes: 6 additions & 2 deletions lib/aws_advanced_ruby_driver_wrapper/utils/rds_utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ module Utils
module RdsUtils
extend self

# The instance host pattern derived for a host that isn't a recognized RDS endpoint. It has no domain,
# so hosts built from it are bare instance identifiers.
BARE_INSTANCE_HOST_PATTERN = '?'

# Authoritative allow-list of AWS regions that can host an RDS/Aurora endpoint.
KNOWN_REGIONS = %w[
af-south-1
Expand Down Expand Up @@ -394,11 +398,11 @@ def rds_instance_name(host)

def rds_instance_host_pattern(host)
prepared = prepared_host(host)
return '?' if blank?(prepared)
return BARE_INSTANCE_HOST_PATTERN if blank?(prepared)

groups = cache_match(prepared, *DNS_PATTERNS)
domain = groups&.[]('domain')
domain ? "?.#{domain}" : '?'
domain ? "?.#{domain}" : BARE_INSTANCE_HOST_PATTERN
end

def rds_region(host)
Expand Down
Loading