Set `inverse_of` on Clusters <-> Applications association

Summary

The calls to cluster.applications will do 36 queries.

inverse_of is not active by default probably since the model/class names aren't expected by active record.

Adding inverse_of to each application association here will reduce cluster.applications to 9 queries.

We should also consider the possible performance improvement of adding it also to the ApplicationCore

Improvements

Query count reduction from 36 to 9 when loading applications. This happens because, when applications get instantiated they also access the cluster: https://gitlab.com/gitlab-org/gitlab-ce/blob/master/app%2Fmodels%2Fclusters%2Fconcerns%2Fapplication_core.rb#L18

examples:

- has_one :application_runner, class_name: 'Clusters::Applications::Runner'
+ has_one :application_runner, class_name: 'Clusters::Applications::Runner', inverse_of: :cluster
...
-        def self.application_name
-          self.to_s.demodulize.underscore
-        end
-
-        belongs_to :cluster, class_name: 'Clusters::Cluster', foreign_key: :cluster_id, inverse_of: :"application_#{application_name}"
+        belongs_to :cluster, class_name: 'Clusters::Cluster', foreign_key: :cluster_id

Risks

Parts of the code that my be expecting the association to be reloaded when doing such things like cluster.application_helm.cluster or application_helm.cluster.application_helm.

Involved components

  • app/models/clusters/cluster.rb
  • app/models/clusters/concerns/application_core.rb

Optional: Missing test coverage

We could write tests to guarantee the amount of query reduction when loading those apps. For instance on the clusters_controller show action.

# psudo code
it 'does only 1 query' do
  query_count = ActiveRecord::QueryRecorder.new { cluster.applications }.count

  expect(query_count).to eq(9)
end
Edited by João Alexandre Cunha