From d1463820c9f0a602d9e262a462bf7d6ff707c2a7 Mon Sep 17 00:00:00 2001 From: Beth Skurrie Date: Fri, 6 Oct 2017 09:51:25 +1100 Subject: [PATCH] fix: database disconnect error when service not accessed frequently Hopefully Closes: https://github.com/pact-foundation/pact_broker/issues/138 --- pact_broker/database_connection.rb | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/pact_broker/database_connection.rb b/pact_broker/database_connection.rb index ae79739..9cca47d 100644 --- a/pact_broker/database_connection.rb +++ b/pact_broker/database_connection.rb @@ -16,5 +16,25 @@ def create_database_connection(logger) credentials[:port] = ENV['PACT_BROKER_DATABASE_PORT'].to_i end - Sequel.connect(credentials.merge(logger: DatabaseLogger.new(logger), encoding: 'utf8')) + ## + # Sequel by default does not test connections in its connection pool before + # handing them to a client. To enable connection testing you need to load the + # "connection_validator" extension like below. The connection validator + # extension is configurable, by default it only checks connections once per + # hour: + # + # http://sequel.rubyforge.org/rdoc-plugins/files/lib/sequel/extensions/connection_validator_rb.html + # + # + # A gotcha here is that it is not enough to enable the "connection_validator" + # extension, we also need to specify that we want to use the threaded connection + # pool, as noted in the documentation for the extension. + # + # -1 means that connections will be validated every time, which avoids errors + # when databases are restarted and connections are killed. This has a performance + # penalty, so consider increasing this timeout if building a frequently accessed service. + connection = Sequel.connect(credentials.merge(logger: DatabaseLogger.new(logger), encoding: 'utf8')) + connection.extension(:connection_validator) + connection.pool.connection_validation_timeout = -1 + connection end