Skip to content

Commit b9b1252

Browse files
authored
Merge pull request #1235 from ctti-clinicaltrials/improve-public-db-connection-logic
Improve public db connection logic
2 parents 05aa077 + 07ec6c4 commit b9b1252

File tree

2 files changed

+35
-6
lines changed

2 files changed

+35
-6
lines changed

app/models/util/db_manager.rb

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,32 @@ def initialize(params={})
1919
##### connection management #####
2020

2121
def public_connection
22-
connection = PublicBase.connection
23-
connection.schema_search_path = @schema
24-
# puts "public connection: #{connection.schema_search_path}"
25-
connection
22+
max_attempts = 3
23+
attempt = 0
24+
backoff_time = 20
25+
26+
begin
27+
attempt += 1
28+
connection = PublicBase.connection
29+
connection.schema_search_path = @schema
30+
connection.execute("SELECT 1")
31+
return connection
32+
rescue PG::ConnectionBad, ActiveRecord::StatementInvalid => e
33+
if attempt < max_attempts
34+
log("Public database connection error: #{e.message}. Retrying in #{backoff_time}s (#{attempt}/#{max_attempts})")
35+
36+
PublicBase.connection_pool.disconnect! # Force reconnection
37+
sleep(backoff_time)
38+
39+
backoff_time *= 2 # Exponential backoff
40+
retry
41+
else
42+
msg = "Failed to establish public database connection after #{max_attempts} attempts: #{e.message}"
43+
log(msg)
44+
event&.add_problem("#{Time.zone.now}: #{msg}")
45+
raise e
46+
end
47+
end
2648
end
2749

2850
def staging_connection
@@ -171,6 +193,10 @@ def restore_from_url(params = {})
171193
# 2. if successful restore to public db
172194
def refresh_public_db
173195
restore_database(public_connection, fm.pg_dump_file)
196+
rescue => e
197+
error_msg = "Failed to refresh public database: #{e.message}"
198+
log(error_msg)
199+
event&.add_problem("#{Time.zone.now}: #{error_msg}")
174200
end
175201

176202
def run_command_line(cmd)

app/models/util/updater_v2.rb

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,11 @@ def worker
6565
end
6666

6767
def db_mgr
68-
# makes it "singleton-like" inside the class
69-
@db_mgr ||= Util::DbManager.new(event: @load_event, schema: @schema)
68+
if @db_mgr.nil?
69+
@db_mgr = Util::DbManager.new(event: @load_event, schema: @schema)
70+
else
71+
@db_mgr.event = @load_event # always has acccess to the latest event
72+
end
7073
end
7174

7275
def update_current_studies

0 commit comments

Comments
 (0)