rails / solid_cache

A database-backed ActiveSupport::Cache::Store
MIT License
888 stars 62 forks source link

Issue with Multi-Shard Databases and Rails Database Selector in Read-Only Mode #214

Closed Dandush03 closed 2 months ago

Dandush03 commented 2 months ago

When using multi-shard databases with the default Rails configuration for sharding, issues arise when attempting to write to the database while in read-only mode. The default configuration is as follows:

Rails.application.configure do
  config.active_record.database_selector = { delay: 2.seconds }
  config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
  config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
end

The issue occurs because, in read-only mode, the connection attempts to load the following class:

SolidCache::Connections::Unmanaged.new

This leads to a failure since the connection persists in read-only mode, causing the operation to break when a write is attempted.

Solution

To resolve this, I updated the configuration from using database to databases, and enclosed the database name in a single-element array within the solid_cache.yml file. This modification forces the system to load:

SolidCache::Connections::Single.new(names.first)

By doing this, the issue was resolved, as it properly handles the connection in the correct mode.

Before

Here’s the original solid_cache.yml configuration that caused the issue:

default: &default
  database: solid_cache
  store_options:
    max_age: <%= 1.week.to_i %>
    max_size: <%= 256.megabytes %>
    namespace: <%= Rails.env %>

development:
  <<: *default

test:
  <<: *default

production:
  <<: *default

After

This is the updated solid_cache.yml configuration that resolved the issue:

default: &default
  databases: [solid_cache]
  store_options:
    max_age: <%= 1.week.to_i %>
    max_size: <%= 256.megabytes %>
    namespace: <%= Rails.env %>

development:
  <<: *default

test:
  <<: *default

production:
  <<: *default

Reference You can find the specific lines in question that caused the issue here: https://github.com/rails/solid_cache/blob/main/lib/solid_cache/connections.rb#L5