Skip to content

Instantly share code, notes, and snippets.

@jacaetevha
Forked from qerub/sequel_reconnector.rb
Created September 28, 2012 17:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jacaetevha/3801154 to your computer and use it in GitHub Desktop.
Save jacaetevha/3801154 to your computer and use it in GitHub Desktop.
Rack middleware that makes sure requests don't get a dead Sequel connection
class SequelReconnector
RETRY_LIMIT = 10 # Match this to your connection pool size.
def initialize(app, db)
@app = app
@db = db
end
def call(env)
retries = 0
connected = false
begin
@db.synchronize do
@db.run(@db.select(1).sql)
connected = true
@app.call(env)
end
rescue Sequel::DatabaseDisconnectError
if connected || retries > RETRY_LIMIT
raise
else
if retries > 0
@db.loggers.each do |logger|
logger.warn("SequelReconnector: Retrying connection...")
end
end
retries += 1
retry
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment