Last active
October 5, 2016 17:46
-
-
Save fnordfish/19e6b53610c4d8b446afeff52bdacf24 to your computer and use it in GitHub Desktop.
An experimental Sidekiq middleware that validates the Sequel connection before each run.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module SidekiqSequel | |
| module Middleware | |
| class Server | |
| attr_reader :db | |
| def initialize(options = nil) | |
| @db = options[:db] | |
| @max_retry = options.fetch(:max_retry, 5) | |
| @error_classes = @db.send(:database_error_classes).dup.freeze | |
| end | |
| def call(_worker, _job, _queue) | |
| validate_connection | |
| yield | |
| end | |
| def validate_connection | |
| # This forces the use of `acquire` which will raises a | |
| # DatabaseDisconnectError, but also cleaning this connection from | |
| # the connection pool correctly | |
| db.run(test_connection_sql) | |
| rescue ::Sequel::DatabaseDisconnectError, *@error_classes | |
| if (@max_retry -= 1) >= 0 | |
| retry | |
| else | |
| raise $! | |
| end | |
| end | |
| def test_connection_sql | |
| @test_connection_sql ||= db.select(nil).sql | |
| end | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment