Skip to content

Commit 614d1d9

Browse files
committed
Track the last time we've seen DB connection activity
1 parent c90e7cf commit 614d1d9

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

activerecord/lib/active_record/connection_adapters/abstract_adapter.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,7 @@ def initialize(config_or_deprecated_connection, deprecated_logger = nil, depreca
168168
@default_timezone = self.class.validate_default_timezone(@config[:default_timezone])
169169

170170
@raw_connection_dirty = false
171+
@last_activity = nil
171172
@verified = false
172173
end
173174

@@ -343,6 +344,13 @@ def seconds_idle # :nodoc:
343344
Process.clock_gettime(Process::CLOCK_MONOTONIC) - @idle_since
344345
end
345346

347+
# Seconds since this connection last communicated with the server
348+
def seconds_since_last_activity # :nodoc:
349+
if @raw_connection && @last_activity
350+
Process.clock_gettime(Process::CLOCK_MONOTONIC) - @last_activity
351+
end
352+
end
353+
346354
def unprepared_statement
347355
cache = prepared_statements_disabled_cache.add?(object_id) if @prepared_statements
348356
yield
@@ -670,6 +678,7 @@ def reconnect!(restore_transactions: false)
670678

671679
enable_lazy_transactions!
672680
@raw_connection_dirty = false
681+
@last_activity = Process.clock_gettime(Process::CLOCK_MONOTONIC)
673682
@verified = true
674683

675684
reset_transaction(restore: restore_transactions) do
@@ -689,6 +698,7 @@ def reconnect!(restore_transactions: false)
689698
end
690699
end
691700

701+
@last_activity = nil
692702
@verified = false
693703

694704
raise translated_exception
@@ -763,6 +773,7 @@ def verify!
763773
@raw_connection = @unconfigured_connection
764774
@unconfigured_connection = nil
765775
configure_connection
776+
@last_activity = Process.clock_gettime(Process::CLOCK_MONOTONIC)
766777
@verified = true
767778
return
768779
end
@@ -1033,6 +1044,7 @@ def with_raw_connection(allow_retry: false, materialize_transactions: true)
10331044
# Barring a known-retryable error inside the query (regardless of
10341045
# whether we were in a _position_ to retry it), we should infer that
10351046
# there's likely a real problem with the connection.
1047+
@last_activity = nil
10361048
@verified = false
10371049
end
10381050

@@ -1047,6 +1059,7 @@ def with_raw_connection(allow_retry: false, materialize_transactions: true)
10471059
# `with_raw_connection` block only when the block is guaranteed to
10481060
# exercise the raw connection.
10491061
def verified!
1062+
@last_activity = Process.clock_gettime(Process::CLOCK_MONOTONIC)
10501063
@verified = true
10511064
end
10521065

0 commit comments

Comments
 (0)