Repository navigation
Refactor connection specification and connection handler - #37388
casperisfine wants to merge 1 commit into
Conversation
|
I agree it makes sense, within the context of our new object hierarchy, that there is a level of object that owns a particular DB schema (and later, in turn, a particular [shard] instance of that schema) -- having several unconnected objects trying to cross-manage that seems like a pain. However, while I see advanced use-case value in being able to change the active role on a per-handler basis, I think it's important for the simple case to maintain the concept of a [thread-]global current role -- not necessarily actively switching between objects, but perhaps with https://github.com/rails/rails/pull/37388/files#diff-7735c67f539e7d1e2908a4d5d8909c24R1013 looking more like: current_roles.fetch(object_id) do
# (note this is not an assignment, so it'll automatically follow any changes in the global setting)
global = Thread.current.thread_variable_get(:ar_connection_role)
role_to_config.key?(global) ? global : Base.writing_role
end |
|
I think that there's a lot of value in doing it this new way, but I'm really worried about the big changes this will require to GitHub's codebase, especially after doing some pretty major changes just to get to 3-tier configs working. The concern I have here is that we won't be able to maintain both versions in GitHub for 6.0 and 6.1 and that maintaining 2 ways to swap databases in our application will be a lot to ask of feature teams. I don't think we can outright break the API and expectations that were set in 6.0. |
|
@eileencodes can I ask which APIs you are using?
@matthewd totally agree, but seems like you missed that |
|
@casperisfine no I saw that |
|
The way I'm reading this is we'll need to change our application like the below to maintain both API's while since 6.0 and 6.1 will behave differently. This just isn't sustainable for feature teams to keep up with. if GitHub.rails_6_0?
ActiveRecord::Base.connected_to(role: x) do
SomeModel.where(id: 1)
SomeOtherModelNowThatWeCantUseHandlers.where(id: 2)
end
else
SomeModelName.connected_to(role: x) do
SomeModel.where(id: 1)
end
SomeOtherModelNowThatWeCantUseHandlers.connected_to(role: x) do
SomeOtherModelNowThatWeCantUseHandlers.where(id: 2)
end
endWe also do some testing with |
|
Before we knew all queries inside of |
|
@matthewd Oh! I think I get it now. And it also seems that it would indeed answer @eileencodes concerns. @eileencodes just to make sure we're on the same page: The current state of the PR doesn't require to use However, I think I now understand how you need the API to be used. So would you be ok with this: ActiveRecord::Base.connected_to(role: :reading) do
ApplicationRecord.current_role # => :reading
AnimalBase.current_role # => :reading
end
AnimalBase.connected_to(role: :reading) do
ApplicationRecord.current_role # => :writing
AnimalBase.current_role # => :reading
endIn short, |
|
The update you sent will work for us as we use ActiveRecord::Base.connected_to(role: :reading) do
ApplicationRecord.current_role # => :reading
AnimalBase.current_role # => :reading
end
AnimalBase.connected_to(role: :reading) do
ApplicationRecord.current_role # => :writing
AnimalBase.current_role # => :reading
endOne question I have about the above is would exiting the block return the queries to default to Ar::Base? Or would exiting the block leave the requests on |
There was a problem hiding this comment.
We should be able to pass db_config here directly
There was a problem hiding this comment.
Will we be removing this entirely?
There was a problem hiding this comment.
Seems like we should at least deprecate the _pool_name parameter if we can't remove it yet for backwards compatibility reasons.
There was a problem hiding this comment.
@dylanahsmith resolve is a private API, we don't need to deprecate it.
There was a problem hiding this comment.
Great. We should just remove it in that case.
| def resolve(config_or_env, _pool_name = nil) | |
| def resolve(config_or_env) |
There was a problem hiding this comment.
I'd like to, but I'm not sure it's an API breakage or not, so I left it.
There was a problem hiding this comment.
🔥 it. Anything with :nodoc or inside a nodoc constant can be removed without deprecation.
There was a problem hiding this comment.
Since the resolve call in lookup is no longer setting the :name key, I don't think it will even be there anymore. If we were going to keep this method, then I think this line needs to be updated to just get the name from the db_config directly. However, it looks like this method is considered private and this PR makes it unused, so we could just remove it entirely.
Well, the way I see it, you should be able to call IMO there is a use case for having read only access to one db, but write access to the other.
Not sure I understand your question. When you exit the block you are back to the previous state, so for each model you are back to query the default role (most likely |
1684232 to
c6f5040
Compare
|
I just pushed a quick change such as: >> ActiveRecord::Base.connected_to(role: :reading) { p [ActiveRecord::Base.current_role, ApplicationRecord.current_role, AnimalBase.current_role] }
[:writing, :writing, :writing]
=> [:writing, :writing, :writing]
>> ApplicationRecord.connected_to(role: :reading) { p [ActiveRecord::Base.current_role, ApplicationRecord.current_role, AnimalBase.current_role] }
[:writing, :reading, :writing]
=> [:writing, :reading, :writing]
>> AnimalBase.connected_to(role: :reading) { p [ActiveRecord::Base.current_role, ApplicationRecord.current_role, AnimalBase.current_role] }
[:writing, :writing, :reading]
=> [:writing, :writing, :reading]I'll handle other suggestions and start fixing tests. |
758b4e0 to
f636d1b
Compare
bf4b0c3 to
e1d3f03
Compare
1afa104 to
b01b9a0
Compare
b01b9a0 to
b7b004b
Compare
b7b004b to
436a1a9
Compare
70dcec9 to
879ec4f
Compare
d2d3044 to
ef861ca
Compare
6b2166a to
10f203f
Compare
0ffdd04 to
9ecfd75
Compare
9ecfd75 to
a5c2d6b
Compare
There was a problem hiding this comment.
This change might seem a bit weird, and I agree, however I'm afraid it's a lesser evil until we get further.
Later on we should have an object tree that represent the different databases, so it will be easy to simply create a sublcass, and give it a reference to the schema it maps to.
However right now, the topology is still very much held by the model classes, so only proper way to access the animals connection, is to inherit from AnimalBase, hence this change. The constantize is just an unfortunate consequence of this.
But again, I'm confident we'll be able to clean that up down the road, so I hope it's not too much of a deal breaker.
There was a problem hiding this comment.
The change we did in this PR revealed a bunch of leaks in the ActiveRecord test suite. One of the main issue
was tests doing something like
test 'foo' do
ActiveRecord::Base.connects_to(writing: :arunit2, reading: :other_db)
endThe problem with this is that after that test runs, ActiveRecord::Base connection_handler will hold the connection on the activerecord_unittest2 db (and not the regular activerecord_unittest).
I started fixing tests independently but ended up in a huge rabbit hole so I opted for a "global" state reset instead of doing a @previous_connection_handlers = ..., ensure ... in a lot of places
3984898 to
2b827ed
Compare
2b827ed to
d298ef4
Compare
|
Hey friends , this PR is ready to be reviewed, we managed to get a green build 🙇 |
eileencodes
left a comment
There was a problem hiding this comment.
Thanks for working on this 😄 I did a quick review, but want to look closer when I'm back in the office on Friday.
We definitely want to move away from connection_specification_name because it ties a connection config to a class. I think by moving that to the handler key we're not fixing the underlying problem which is a config has no idea what class it belongs to until it gets connected. I'm worried this implementation hides that "problem" and makes it harder to drop the class entirely.
There's a small bug in here as well. If we continue in this direction we need to treat "ActiveRecord::Base" and "ApplicationRecord" the same otherwise we end up with duplicate connections. The problem with that can be seen here:
On boot in development mode:
>> ActiveRecord::Base.connection_handlers
=> {"ActiveRecord::Base"=>#<ActiveRecord::ConnectionAdapters::ConnectionHandler:0x00007fbc767c4f18 @roles=#<Concurrent::Map:0x00007fbc767c4e78 entries=1 default_proc=nil>>}
After calling another connection class:
>> MealBase
=> MealBase(abstract)
>> ActiveRecord::Base.connection_handlers
=> {"ActiveRecord::Base"=>#<ActiveRecord::ConnectionAdapters::ConnectionHandler:0x00007fbc767c4f18 @roles=#<Concurrent::Map:0x00007fbc767c4e78 entries=1 default_proc=nil>>, "ApplicationRecord"=>#<ActiveRecord::ConnectionAdapters::ConnectionHandler:0x00007fbc7c025c20 @roles=#<Concurrent::Map:0x00007fbc7c025bd0 entries=2 default_proc=nil>>, "MealBase"=>#<ActiveRecord::ConnectionAdapters::ConnectionHandler:0x00007fbc78427598 @roles=#<Concurrent::Map:0x00007fbc78427548 entries=2 default_proc=nil>>}
My biggest concern is the ways in which this is changing the public API and how that will affect applications and libraries
There was a problem hiding this comment.
I'm not quite following what's being checked here. If there's a pool in the list and we have a connection then why does this end up raising?
There was a problem hiding this comment.
Thanks for pointing that out, just realised it it wasn't 100% correct.
If there's a pool in the list and we have a connection then why does this end up raising?
It end up raising because there is no pool for the given role. What I want to do here is grab any connection pool (doesn't matter which role) in order to get the database name. This comes with the assumptions that each roles (writing, reading) on the handler will connect to the same db
There was a problem hiding this comment.
Why does ActiveRecord::Base need to be treated special here?
There was a problem hiding this comment.
It doesn't have to, but it makes it so that ActiveRecord::Base.connection.schema_migration == ActiveRecord::SchemaMigration, which is nicer than getting an anonymous class, and better for backward compat.
All this is very temporary though, I really don't like the current schema_migration implementation, it's just hard to do better for now.
There was a problem hiding this comment.
This is a public API so changing this to take role when role isn't the same thing as spec_name could break a lot of apps
There was a problem hiding this comment.
This is also part of the public API.
d298ef4 to
018d85f
Compare
Right now, here's what a two DB setup, each with one writer and one reader looks like:
```ruby
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
connects_to database: { writing: :primary, reading: :primary_replica }
end
class AnimalBase < ApplicationRecord
self.abstract_class = true
connects_to database: { writing: :animals, reading: :animals_replica }
end
```
With the following state:
```
>> ApplicationRecord.connection_specification_name
=> "primary"
>> AnimalBase.connection_specification_name
=> "AnimalBase"
>> ActiveRecord::Base.connection_handlers.keys
=> [:writing, :reading]
>> ActiveRecord::Base.connection_handlers.fetch(:reading).connection_pool_names
=> ["primary", "AnimalBase"]
```
So in other words, there's one ConnectionHandler instance per role.
Each ConnectionHandler connects to different "database schemas".
It should be the inverse, there should be one ConnectionHandler per
"database schema" (primary vs animals), and it should handle all the
roles of that schema (writing, reading, etc).
With this PR:
```
>> ApplicationRecord.connection_handler.connection_pool_names
=> [:writing, :reading]
>> AnimalBase.connection_handler.connection_pool_names
=> [:writing, :reading]
```
Whenever you call connects_to on a model, it assign a new
ConnectionHandler on it, and from there the inheritance chain take
care of accessing the right set of connections.
Also rather then switching handlers, we only switch the currently
selected role:
```
>> AnimalBase.current_role
=> :writing
>> AnimalBase.connected_to(role: :reading) { AnimalBase.current_role }
=> :reading
>> AnimalBase.connected_to(role: :reading) { ApplicationRecord.current_role }
=> :writing
```
Co-authored-by: Edouard Chin <[email protected]>
018d85f to
53e968a
Compare
| end | ||
|
|
||
| attr_writer :connection_specification_name | ||
| attr_writer :connection_handler |
There was a problem hiding this comment.
Can we instead just have the model specify the schema name?
class_attribute :schema_name
alias_method :connection_specification_name, :schema_name
alias_method :connection_specification_name=, :schema_name=
deprecate :connection_specification_name, connection_specification_name=then detach the connection handling from the model and just look it up from the model using the schema_name. That way we can do things like switch the connection for a schema as part of shard migrations and the connection switch affect the sharded models.
There was a problem hiding this comment.
Ultimately that's where I'd like to get at. We've tried that with Édouard, but it broke way too many test, so we decided to delay that change for a later iteration.
This PR is an alternate solution to rails#37388. While there are benefits to merging rails#37388 it changes the public API and swaps around existing concepts for how connection management works. The changes are backwards-incompatible and pretty major. This will have a negative impact on gems and applications relying on how conn management currently works. **Background:** Shopify and other applications need sharding but Rails has made it impossible to do this because a handler can only hold one connection pool per class. Sharded apps need to hold multiple connections per handler per class. This PR aims to solve only that problem. **What this PR does:** In this PR we've added a `RoleManager` class that can hold multiple `Roles`. Each `Role` holds the `db_config`, `connection_specification_name`, `schema_cache` and `pool`. By default the `RoleManager` holds a single reference from a `default` key to the `Role` instance. A sharded/multi-tenant app can pass an optional second argument to `remove_connection`, `retrieve_connection_pool`, `establish_connection` and `connected?` on the handler, thus allowing for multiple connections belonging to the same class/handler without breaking backwards compatibility. By using the `RoleManager` we can avoid altering the public API, moving around handler/role concepts, and achieve the internal needs for establishing multiple connections per handler per class. **A note about why we opened this PR:** We very much appreciate the work that went into rails#37388 and in no way mean to diminish that work. However, it breaks the following public APIs: * `#retrieve_connection`, `#connected?`, and `#remove_connection` are public methods on handler and can't be changed from taking a spec to a role. * The knowledge that the handler keys are symbols relating to a role (`:writing`/`:reading`) is public - changing how handlers are accessed will break apps/libraries. In addition it doesn't solve the problem of mapping a single connection to a single class since it has a 1:1 mapping of `class (handler) -> role (writing) -> db_config`. Multiple pools in a writing role can't exist in that implementation. The new PR solves this by using the `RoleManager` to hold multiple connection objects for the same class. This lets a handler hold a role manager which can hold as many roles for that writer as the app needs. **Regarding the `Role` name:** When I originally designed the API for multiple databases, it wasn't accidental that handler and role are the same concept. Handler is the internal concept (since that's what was there already) and Role was the public external concept. Meaning, role and handler were meant to be the same thing. The concept here means that when you switch a handler/role, Rails automatically can pick up the connection on the other role by knowing the specification name. Changing this would mean not just that we need to rework how GitHub and many many gems work, but also means retraining users of Rails 6.0 that all these concepts changed. Since this PR doesn't move around the concepts in connection management and instead creates an intermediary between `handler` and `role` to manage the connection data (`db_config`, `schema_cache`, `pool`, and `connection_specification`) we think that `Role` and `RoleManager` are the wrong name. We didn't change it yet in this PR because we wanted to keep change churn low for initial review. We also haven't come up with a better name yet. 😄 **What this PR does not solve:** Our PR here solves a small portion of the problem - it allows models to have multiple connections on a class. It doesn't aim to solve any other problems than that. Going forward we'll need to still solve the following problems: * `DatabaseConfig` doesn't support a sharding configuration * `connects_to`/`connected_to` still needs a way to switch connections for shards * Automatic switching of shards * `connection_specification_name` still exists **The End** Thanks for reading this far. These problems aren't easy to solve. John and I spent a lot of time trying different things and so I hope that this doesn't come across as if we think we know better. I would have commented on the other PR what changes to make but we needed to try out different solutions in order to get here. Ultimately we're aiming to change as little as the API as possible. Even if the handler/role -> manager -> db_config/pool/etc isn't how we'd design connection management if we could start over, we also don't want to break public APIs. It's important that we make things better while maintaining compatibility. The `RoleManager` class makes it possible for us to fix the underlying problem while maintaining all the backwards compatibility in the public API. We all have the same goal; to add sharding support to Rails. Let me know your thoughts on this change in lieu of rails#37388 and if you have questions. Co-authored-by: John Crepezzi <[email protected]>
Followup: #37296
There is a lot of tests to fix on this PR, but I tested it against a small application, it's mostly functional. I'd just like to validate the direction it's taking before investing a lot more time into it.
Current state
Right now, here's what a two DB setup, each with one writer and one reader looks like:
With the following state:
So in other words, there's one
ConnectionHandlerinstance perrole. And eachConnectionHandlerconnects to different "database schemas"Where this PR is trying to go
IMO it should be the inverse, there should be one
ConnectionHandlerper "database schema" (primaryvsanimals), and it should handle all the roles of that schema (writing,reading, etc).With this PR:
Whenever you call
connects_toon a model, it assign a newConnectionHandleron it, and from there the inheritance chain take care of accessing the right set of connections.Also rather then switching handlers, we only switch the currently selected role:
@matthewd @eileencodes @seejohnrun at this stage I'd like your opinions here, because It's heavily changing how multidb connection works, and I think at least part of the backward compatibility will have to be broken (not 100% sure yet).
cc @rafaelfranca @Edouard-chin @etiennebarrie