Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),

## [Unreleased]

### :magic_wand: Added
- The `pg_query_timeout_sec` property for PostgreSQL (`pg`): a client-side timeout, in seconds, for the wrapper's own queries.
- **Queries covered:** topology, host role checks, dialect detection, Blue/Green status, the failover `ROLLBACK`, and the KMS Encryption Plugin's key store. It never applies to application queries.
- **On expiry:** the query fails with a `PgDriverDialect::QueryTimeoutError` (a `PG::ConnectionBad`) that the wrapper treats as a network error (`ActiveRecord::ConnectionFailed` under `aws_postgresql`). A connection the wrapper opened itself is closed. The application's own connection, which the failover `ROLLBACK` can run on, is left open for its owner to close, or swapped under a successful failover.
- **Default:** `0` (no timeout), except for the topology and Blue/Green monitors, which use `5` seconds unless the property is set and can be overridden by `topology_monitoring_pg_query_timeout_sec` and `bg_monitoring_pg_query_timeout_sec` respectively, setting these to `0` disables the timeout.

### :bug: Fixed
- Fixed the `aws_postgresql` ActiveRecord adapter keeping ActiveRecord's prepared statement cache when a failover happened while ActiveRecord checked a connection (`active?`) or reset it (`reset!`). Those calls bypass the adapter's error translation, so after the failover every query prepared before it failed with `Method invoked against old connection` until ActiveRecord discarded the connection. The adapter now clears the cache and re-applies the connection's settings there too.
- **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.
Expand Down
4 changes: 4 additions & 0 deletions benchmarks/support/benchmark_services.rb
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,10 @@ def db_dialect
end

def update_dialect(_connection); end

def with_query_timeout(_connection, close_on_timeout:, timeout_sec: nil)
yield
end
end

class StubConnectionService
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,17 @@ def dialect?(connection)
result = @driver_dialect.execute(connection, AURORA_UTILS_EXIST_QUERY)
return false unless result.any?
return false unless result.first['aurora_stat_utils'] == 't'
rescue StandardError
rescue StandardError => e
raise if @driver_dialect.query_timeout_error?(e)

return false
end

result = @driver_dialect.execute(connection, TOPOLOGY_EXISTS_QUERY)
!result.nil? && result.any?
rescue StandardError
rescue StandardError => e
raise if @driver_dialect.query_timeout_error?(e)

false
end

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,15 @@ def dialect?(connection)
return false unless
check_existence_queries(@driver_dialect, connection, GLOBAL_STATUS_FUNC_EXISTS_QUERY, GLOBAL_INSTANCE_STATUS_FUNC_EXISTS_QUERY)

result = connection.exec(REGION_COUNT_QUERY)
result = @driver_dialect.execute(connection, REGION_COUNT_QUERY)
return false unless result.any?

row = result.first
aws_region_count = row.is_a?(Hash) ? row.values.first.to_i : row[0].to_i
aws_region_count > 1
rescue StandardError
rescue StandardError => e
raise if @driver_dialect.query_timeout_error?(e)

false
end

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@ def dialect?(connection)

row = result.first
!row['multi_az_db_cluster_source_dbi_resource_id'].nil?
rescue StandardError
rescue StandardError => e
raise if @driver_dialect.query_timeout_error?(e)

false
end

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@ def dialect?(connection)

return true if rds_tools_enabled && !aurora_utils_enabled
end
rescue StandardError
rescue StandardError => e
raise if @driver_dialect.query_timeout_error?(e)

return false
end

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,9 @@ def check_existence_queries(driver_dialect, connection, *queries)
return false if result.nil? || result.none?
end
true
rescue StandardError
rescue StandardError => e
raise if driver_dialect.query_timeout_error?(e)

false
end
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,18 @@ def execute_with_params(connection, sql, params)
raise NotImplementedError
end

# Bounds the wrapper-internal queries (#execute, #execute_with_params) that run on +connection+ inside
# the block to +timeout_sec+ seconds in total. Application queries are never bounded.
# Only the PostgreSQL dialect can bound a query itself (the other drivers have +read_timeout+), so this
# yields unchanged by default.
#
# @param close_on_timeout [Boolean] true if the wrapper owns +connection+ and may close it on timeout,
# false if the application owns it and it must be left open
# @param timeout_sec [Numeric, nil] the bound; nil or non-positive leaves the block unbounded
def with_query_timeout(_connection, close_on_timeout:, timeout_sec: nil)
yield
end

# Rewrites +?+ placeholders into the driver's native placeholder syntax.
# @param sql [String] SQL written with +?+ placeholders
# @return [String]
Expand Down Expand Up @@ -135,6 +147,12 @@ def sql_state(_exception)
nil
end

# Whether +error+ is this driver's timeout for a wrapper-internal query (see #with_query_timeout).
# Dialect detection must not read a timeout as "not this dialect": the answer is unknown, so it has to propagate.
def query_timeout_error?(_error)
false
end

def network_bound_methods
COMMON_NETWORK_BOUND_METHODS
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ module DriverDialects
class PgDriverDialect
include DriverDialect

QUERY_TIMEOUT_SCOPE_KEY = :aws_advanced_ruby_driver_wrapper_pg_query_timeouts
private_constant :QUERY_TIMEOUT_SCOPE_KEY

# Every pg call that talks to the server. A call that is not listed here is handed straight
# to the driver, bypassing the plugin pipeline.
#
Expand Down Expand Up @@ -97,12 +100,51 @@ def connect(host_info, config)
::PG::Connection.new(**prepare_connect_config(host_info, config))
end

# Bounds the wrapper-internal queries (#execute, #execute_with_params) run on +connection+ inside the
# block to +timeout_sec+ seconds in total (one deadline per query, not reset as data arrives).
# libpq has no client-side query timeout, and TCP keepalives or tcp_user_timeout only see the next hop,
# so a database that stops answering behind a proxy would otherwise block a query indefinitely. The wait
# is on the socket, so it holds behind such a proxy.
#
# The scope is the calling fiber and only +connection+; queries on other connections, and every
# application query, are unaffected. A +nil+ or non-positive timeout leaves the block unbounded.
# Nested scopes on the same connection: the innermost wins.
#
# @param close_on_timeout [Boolean] true if the wrapper owns +connection+ (a monitor's, or one it has
# not handed out yet): on timeout it is abandoned and closed. false if the application owns it:
# the error is raised and the connection is left for its owner to close.
# @raise [PgDriverDialect::QueryTimeoutError] from a bounded query that gets no reply in time
def with_query_timeout(connection, close_on_timeout:, timeout_sec: nil)
timeout = timeout_sec.to_f
return yield unless timeout.positive?

scopes = (Thread.current[QUERY_TIMEOUT_SCOPE_KEY] ||= {}.compare_by_identity)
had_previous = scopes.key?(connection)
previous = scopes[connection]
scopes[connection] = [timeout, close_on_timeout]
begin
yield
ensure
if had_previous
scopes[connection] = previous
else
scopes.delete(connection)
end
end
end

def execute(connection, sql)
connection.exec(sql)
timeout, close_on_timeout = query_timeout_for(connection)
return connection.exec(sql) unless timeout

await_result(connection, timeout, close_on_timeout) { connection.send_query(sql) }
end

def execute_with_params(connection, sql, params)
connection.exec_params(sql, params)
timeout, close_on_timeout = query_timeout_for(connection)
return connection.exec_params(sql, params) unless timeout

await_result(connection, timeout, close_on_timeout) { connection.send_query_params(sql, params) }
end

# pg uses numbered +$1+, +$2+ ... placeholders.
Expand Down Expand Up @@ -186,6 +228,11 @@ def sql_state(exception)
exception.result.error_field(::PG::PG_DIAG_SQLSTATE)
end

# The error class is loaded on demand (it needs the pg gem), so check that it is defined before using it.
def query_timeout_error?(error)
defined?(QueryTimeoutError) == 'constant' && error.is_a?(QueryTimeoutError)
end

def network_bound_methods
NETWORK_BOUND_METHODS
end
Expand Down Expand Up @@ -213,6 +260,54 @@ def apply_monitoring_defaults(driver_props)
driver_props[:connect_timeout] ||= DEFAULT_MONITORING_TIMEOUT_SEC
end

# The [timeout_sec, close_on_timeout] in force for +connection+ on this fiber, or nil.
def query_timeout_for(connection)
Thread.current[QUERY_TIMEOUT_SCOPE_KEY]&.[](connection)
end

# Sends a query and waits for its results, giving up when the whole result has not arrived within +timeout+ seconds.
# On timeout a query is still pending on the connection, so it cannot be reused; it is abandoned and
# closed when +close_on_timeout+, and left alone otherwise.
# @raise [PgDriverDialect::QueryTimeoutError] on timeout
def await_result(connection, timeout, close_on_timeout)
yield
deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
last = nil
loop do
while connection.is_busy
remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
unless remaining.positive? && connection.socket_io.wait_readable(remaining)
last&.clear
logger.info(
"Wrapper query timed out after #{timeout}s on #{describe_connection(connection)}; " \
"#{close_on_timeout ? 'closing the connection' : 'leaving the connection open for its owner'}."
)
if close_on_timeout
abandon_connection(connection)
close_connection(connection)
end
# A no-op once loaded; kept for callers that use the dialect without the postgresql entry point.
require_relative 'pg_query_timeout_error'
raise QueryTimeoutError, timeout
end
connection.consume_input
end
result = connection.get_result
break if result.nil?

last&.clear
last = result
end
last&.check
last
end

def describe_connection(connection)
"#{connection.host}:#{connection.port}"
rescue StandardError
'an unknown host'
end

# PG reads transaction state directly from the connection.
# Returns nil for PQTRANS_UNKNOWN (broken) and PQTRANS_ACTIVE (command in flight)
# so SessionStateService falls back to SQL inference.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# frozen_string_literal: true

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Loaded on demand (see PgDriverDialect#await_result): it inherits from PG::ConnectionBad, which needs the pg gem.
require 'pg'

module AwsAdvancedRubyDriverWrapper
module DriverDialects
class PgDriverDialect
# Raised when a wrapper-internal query gets no reply within its timeout (see #with_query_timeout).
#
# It is a +PG::ConnectionBad+, so callers that rescue the driver's connection error handle it, and
# PgErrorHandler#network_error? recognizes it by class. The trailing newline is deliberate: ActiveRecord
# tells a libpq failure (message ends in a newline, the query may have reached the server) from a
# pg-internal one (no newline, never sent) and maps the former to ActiveRecord::ConnectionFailed, which
# is right for a query that was sent. Keep it, and avoid the phrases "connection is closed" and "no
# connection to the server", which ActiveRecord matches first.
class QueryTimeoutError < ::PG::ConnectionBad
def initialize(timeout_sec)
super("wrapper internal query timed out after #{timeout_sec}s\n")
end
end
end
end
end
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,8 @@ def read_only_error_by_sql_state?(sql_state, _error_code = nil)

def connection_bad_network_error?(error)
return false unless defined?(PG::ConnectionBad) && error.is_a?(PG::ConnectionBad)
# A timed-out wrapper query is a connection failure by class, whatever its message says.
return true if @driver_dialect.query_timeout_error?(error)

msg = error.message&.downcase
return false if msg.nil?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ def force_refresh(verify_writer, timeout_sec)
end
else
# Monitoring thread is mid-query. Detach without closing — the monitoring thread will close the
# connection after its query completes (via read_timeout for MySQL or keepalives for PG).
# connection after its query completes (via read_timeout for MySQL or pg_query_timeout_sec for PG).
@monitoring_connection.set(nil, close_old: false)
end
@verified_writer = false
Expand Down Expand Up @@ -395,7 +395,8 @@ def attempt_host_connection(host_info, attempts)
end

def check_host_role(conn)
@service_container.dialect_service.db_dialect.host_role(conn)
dialect_service = @service_container.dialect_service
dialect_service.with_monitoring_query_timeout(conn, @monitoring_wrapper_props) { dialect_service.db_dialect.host_role(conn) }
rescue StandardError => e
logger.debug("[#{@cluster_id}] host_role check failed: #{e.message}")
nil
Expand Down Expand Up @@ -502,7 +503,9 @@ def fetch_topology_and_update_cache(conn)
end

def query_topology(conn)
@topology_utils.query_topology(conn, @initial_host_info, @instance_template)
@service_container.dialect_service.with_monitoring_query_timeout(conn, @monitoring_wrapper_props) do
@topology_utils.query_topology(conn, @initial_host_info, @instance_template)
end
end

def stored_hosts
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ def initialize(
private

def query_topology(conn)
@topology_utils.query_global_topology(conn, initial_host_info, @instance_templates_by_region)
@service_container.dialect_service.with_monitoring_query_timeout(conn, @monitoring_wrapper_props) do
@topology_utils.query_global_topology(conn, initial_host_info, @instance_templates_by_region)
end
end

def resolve_instance_template(instance_id, conn)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -297,10 +297,13 @@ def collect_status
conn = @connection.get
return if conn.nil? || connection_closed?(conn)

return unless status_available?(conn)
dialect_service = @service_container.dialect_service
return unless dialect_service.with_monitoring_query_timeout(conn, @status_monitor_wrapper_props) { status_available?(conn) }

dialect = @service_container.dialect_service.db_dialect
status_entries = parse_status_entries(conn, dialect)
dialect = dialect_service.db_dialect
status_entries = dialect_service.with_monitoring_query_timeout(conn, @status_monitor_wrapper_props) do
parse_status_entries(conn, dialect)
end
status_info = resolve_status_info(status_entries)
apply_status_info(status_info, status_entries)
verify_connection_host(status_info)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,10 @@ def invalidate_current_connection
return unless @service_container.session_state_service.in_transaction?

begin
driver_dialect.execute(conn, 'ROLLBACK')
# The application owns this connection: bound the wait, but leave it open if the ROLLBACK times out.
dialect_service.with_query_timeout(conn, close_on_timeout: false) do
driver_dialect.execute(conn, 'ROLLBACK')
end
rescue StandardError
nil
end
Expand Down Expand Up @@ -534,7 +537,8 @@ def try_original_writer(original_writer, original_writer_still_writer)
def attempt_reader_connection(host_info)
conn = @service_container.plugin_manager.connect(host_info, connection_service.driver_props, false, plugin_to_skip: self)
# Since the roles in the host list might not be accurate, we execute a query to check the instance's role.
role = db_dialect.host_role(conn)
# A candidate connection the wrapper opened and has not handed out, so it may be closed on timeout.
role = dialect_service.with_query_timeout(conn, close_on_timeout: true) { db_dialect.host_role(conn) }

if role == Host::HostRole::READER || @failover_mode != FailoverMode::STRICT_READER
updated_host = host_info.deep_dup(role: role)
Expand Down Expand Up @@ -577,7 +581,9 @@ def verified_connection(is_initial_connection, host_info, driver_props, connect_
end

conn = connect_func.call
if db_dialect.host_role(conn) == Host::HostRole::WRITER
# Not handed to the application yet, so the wrapper may close it on timeout.
role = dialect_service.with_query_timeout(conn, close_on_timeout: true) { db_dialect.host_role(conn) }
Comment thread
sophia-bq marked this conversation as resolved.
Resolved
if role == Host::HostRole::WRITER
host_service.refresh_host_list
return conn
end
Expand Down
Loading