Rails 3 ActiveRecord.skip_callback thread safety

Is this stream of code safe?

MyModel.skip_callback(:save, :before, :my_callback) my_model_instance.update_attributes(attributes) MyModel.set_callback(:save, :before, :my_callback) 

Is it safe to use it to retry a repeater repeater?

Here is an example

 class Blog < ActiveRecord::Base after_save :update_blog_theme, :if => :active_theme_id_changed? # ... private def update_blog_theme # Reuses a previously used BlogTheme or creates a new one blog_theme = BlogTheme.find_by_theme_id_and_blog_id( self.active_theme_id, self.id) blog_theme ||= BlogTheme.create!( :theme_id => active_theme_id, :blog_id => self.id ) Blog.skip_callback(:save, :after, :update_blog_theme) self.update_attributes!(:active_blog_theme_id => blog_theme.id) Blog.set_callback(:save, :after, :update_blog_theme) end end 
+6
source share
1 answer

skip_callback and set_callback are NOT thread safe. I was able to confirm this by trying to create some entries in sidekiq (a threaded asynchronous job processor). As soon as I activate callbacks again, a race condition arises that results in callbacks being called. If I comment on the re-activation code of the callback, there is no problem.

I found several possible solutions to the problem, including two stones:

  • gemstone 'sneaky-save'
  • gem 'skip_activerecord_callbacks'

The hidden gem seems the most direct and intentional. The gem significantly circumvents ActiveRecord storage methods and performs direct sql.

This is also the only thing I can say with confidence that it is thread-safe. It is also a very small and understandable stone. The disadvantage is that it does not cause a check. Thus, you will need to invoke checks yourself.

Anand A. Byte has collected a large number of possible options. I am skeptical that all five options are thread safe. The two gems mentioned above are listed along with other possible options in Ananda's post here: http://www.allerin.com/blog/save-an-object-skipping-callbacks-in-rails-3-application/

+5
source

Source: https://habr.com/ru/post/892934/


All Articles