rails-on-services / apartment

Database multi-tenancy for Rack (and Rails) applications
376 stars 146 forks source link

Apartment::TenantNotFound raised randomly in production #166

Open giovapanasiti opened 3 years ago

giovapanasiti commented 3 years ago

Steps to reproduce

I just deployed my tenant app on digitalocean app platform and digitalocean postgres db

Expected behavior

when the use hit the right subdomain it should switch to the right tenant. It usually works but sometimes sentry caught this error.

Actual behavior

randomly it raises Apartment::TenantNotFound One of the following schema(s) is invalid: "mainapp" "public", "shared_extensions"

System configuration

config.persistent_schemas = ["shared_extensions"]
  config.tenant_names = -> { Account.pluck :subdomain_name }
  config.excluded_models = ["Account", 'ActionMailbox::InboundEmail']
  config.active_record_log = true
  Apartment::Elevators::Subdomain.excluded_subdomains = ["www", "admin", "public", "saladilprealpha"]
  Apartment::Elevators::FirstSubdomain.excluded_subdomains = ["www", "admin", "public", "saladilprealpha"]

....

Rails.application.config.middleware.use Apartment::Elevators::Subdomain
lunks commented 2 years ago

I'm doing a bit of investigation on this and it seems we incorrectly assume an error in connect_to_new is a schema missing error: https://github.com/rails-on-services/apartment/blob/1929f5f76bd654bb0023243d2ca30341761aadb1/lib/apartment/adapters/postgresql_adapter.rb#L85-L87

rpbaltazar commented 2 years ago

@giovapanasiti with the latest version, the work of @lunks has been made available. it does not fix the problem per se but it should allow you to understand what the underlying cause of the problem is. We should probably aim at better erroring in general