From 75a2c7f83314c5e643ca81f39fffc748aa792217 Mon Sep 17 00:00:00 2001 From: Felipe Sateler Date: Thu, 20 Apr 2023 12:35:17 -0400 Subject: [PATCH] Don't fail lock release if the connection was disconnected If the connection is broken, then the lock was released because the session is aborted. Thus there is no need to fail. --- lib/with_advisory_lock/postgresql.rb | 2 ++ test/lock_test.rb | 6 ++++++ test/test_helper.rb | 1 + 3 files changed, 9 insertions(+) diff --git a/lib/with_advisory_lock/postgresql.rb b/lib/with_advisory_lock/postgresql.rb index ae369cb..e5c8065 100644 --- a/lib/with_advisory_lock/postgresql.rb +++ b/lib/with_advisory_lock/postgresql.rb @@ -14,6 +14,8 @@ def release_lock pg_function = "pg_advisory_unlock#{shared ? '_shared' : ''}" execute_successful?(pg_function) rescue ActiveRecord::StatementInvalid => e + # If something goes real bad, pg will close the connection. in that case the lock is no longer held + return if e.message =~ /PG::ConnectionBad:/ raise unless e.message =~ / ERROR: +current transaction is aborted,/ begin diff --git a/test/lock_test.rb b/test/lock_test.rb index 1a6e583..1d22da1 100644 --- a/test/lock_test.rb +++ b/test/lock_test.rb @@ -56,6 +56,12 @@ thread_with_lock.kill end + + it 'handles lost connection gracefully' do + Tag.with_advisory_lock(lock_name) { Tag.connection.disconnect! } + + assert_nil(Tag.current_advisory_lock) + end end describe '.with_advisory_lock!' do diff --git a/test/test_helper.rb b/test/test_helper.rb index f28bb1b..50034b6 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -37,6 +37,7 @@ def env_db module MiniTest class Spec before do + ActiveRecord::Base.establish_connection ENV['FLOCK_DIR'] = Dir.mktmpdir Tag.delete_all TagAudit.delete_all