|
3 | 3 | require 'sidekiq' |
4 | 4 | require 'sidekiq-scheduler' |
5 | 5 |
|
6 | | -# Only configure Sidekiq if Redis is available |
7 | | -if ENV['REDIS_URL'].present? |
| 6 | +# Gracefully handle Redis unavailability |
| 7 | +def configure_sidekiq_with_retry |
| 8 | + return false unless ENV['REDIS_URL'].present? |
| 9 | + |
| 10 | + # Test Redis connection before configuring Sidekiq |
| 11 | + begin |
| 12 | + redis_url = ENV['REDIS_URL'] |
| 13 | + Rails.logger.info "Testing Redis connection: #{redis_url.gsub(/:[^:@]+@/, ':***@')}" |
| 14 | + |
| 15 | + # Quick connection test with timeout |
| 16 | + redis_client = RedisClient.new(url: redis_url, timeout: 2.0) |
| 17 | + redis_client.call('PING') |
| 18 | + redis_client.close |
| 19 | + |
| 20 | + Rails.logger.info "✓ Redis connection successful" |
| 21 | + true |
| 22 | + rescue => e |
| 23 | + Rails.logger.error "✗ Redis connection failed: #{e.class} - #{e.message}" |
| 24 | + Rails.logger.error " Sidekiq and background jobs will be disabled" |
| 25 | + Rails.logger.error " Backtrace: #{e.backtrace.first(3).join("\n ")}" |
| 26 | + false |
| 27 | + end |
| 28 | +end |
| 29 | + |
| 30 | +# Only configure Sidekiq if Redis is actually reachable |
| 31 | +if configure_sidekiq_with_retry |
8 | 32 | Sidekiq.configure_server do |config| |
9 | | - config.redis = { url: ENV['REDIS_URL'] } |
| 33 | + config.redis = { |
| 34 | + url: ENV['REDIS_URL'], |
| 35 | + network_timeout: 5, |
| 36 | + pool_timeout: 5 |
| 37 | + } |
10 | 38 |
|
11 | 39 | config.on(:startup) do |
12 | 40 | schedule_file = Rails.root.join('config', 'sidekiq.yml') |
|
21 | 49 | end |
22 | 50 |
|
23 | 51 | Sidekiq.configure_client do |config| |
24 | | - config.redis = { url: ENV['REDIS_URL'] } |
| 52 | + config.redis = { |
| 53 | + url: ENV['REDIS_URL'], |
| 54 | + network_timeout: 5, |
| 55 | + pool_timeout: 5 |
| 56 | + } |
25 | 57 | end |
| 58 | + |
| 59 | + Rails.logger.info "✓ Sidekiq configured successfully" |
26 | 60 | else |
27 | | - Rails.logger.warn "Redis not configured - Sidekiq will not be available. Background jobs will fail." |
| 61 | + Rails.logger.warn "⚠ Redis not available - Sidekiq disabled. Background jobs will not run." |
| 62 | + Rails.logger.warn " Check REDIS_URL environment variable and Redis service status" |
28 | 63 | end |
0 commit comments