|
| 1 | +require 'minitest_helper' |
| 2 | + |
| 3 | +describe "with_advisory_lock" do |
| 4 | + it "adds with_advisory_lock to ActiveRecord classes" do |
| 5 | + assert Tag.respond_to?(:with_advisory_lock) |
| 6 | + end |
| 7 | + |
| 8 | + it "adds with_advisory_lock to ActiveRecord instances" do |
| 9 | + assert Tag.new.respond_to?(:with_advisory_lock) |
| 10 | + end |
| 11 | + |
| 12 | + def find_or_create_at_even_second(run_at, with_advisory_lock) |
| 13 | + sleep(run_at - Time.now.to_f) |
| 14 | + name = run_at.to_s |
| 15 | + if with_advisory_lock |
| 16 | + Tag.with_advisory_lock(name) do |
| 17 | + Tag.find_by_name(name) || Tag.create!(:name => name) |
| 18 | + end |
| 19 | + else |
| 20 | + Tag.find_by_name(name) || Tag.create!(:name => name) |
| 21 | + end |
| 22 | + end |
| 23 | + |
| 24 | + def run_workers(with_advisory_lock) |
| 25 | + start_time = Time.now.to_i + 2 |
| 26 | + threads = @workers.times.collect do |
| 27 | + Thread.new do |
| 28 | + begin |
| 29 | + ActiveRecord::Base.connection.reconnect! |
| 30 | + @iterations.times do |ea| |
| 31 | + find_or_create_at_even_second(start_time + (ea * 2), with_advisory_lock) |
| 32 | + end |
| 33 | + ensure |
| 34 | + ActiveRecord::Base.connection.close |
| 35 | + end |
| 36 | + end |
| 37 | + end |
| 38 | + threads.each { |ea| ea.join } |
| 39 | + puts "Created #{Tag.all.size} (lock = #{with_advisory_lock})" |
| 40 | + end |
| 41 | + |
| 42 | + before :each do |
| 43 | + @iterations = 5 |
| 44 | + @workers = 7 |
| 45 | + end |
| 46 | + |
| 47 | + it "parallel threads create multiple duplicate rows" do |
| 48 | + run_workers(with_advisory_lock = false) |
| 49 | + if Tag.connection.adapter_name == "SQLite" && RUBY_VERSION == "1.9.3" |
| 50 | + Tag.all.size.must_equal @iterations # <- sqlite on 1.9.3 doesn't create dupes IKNOWNOTWHY |
| 51 | + else |
| 52 | + Tag.all.size.must_be :>, @iterations # <- any duplicated rows will make me happy. |
| 53 | + TagAudit.all.size.must_be :>, @iterations # <- any duplicated rows will make me happy. |
| 54 | + Label.all.size.must_be :>, @iterations # <- any duplicated rows will make me happy. |
| 55 | + end |
| 56 | + end |
| 57 | + |
| 58 | + it "parallel threads with_advisory_lock don't create multiple duplicate rows" do |
| 59 | + run_workers(with_advisory_lock = true) |
| 60 | + Tag.all.size.must_equal @iterations # <- any duplicated rows will NOT make me happy. |
| 61 | + TagAudit.all.size.must_equal @iterations # <- any duplicated rows will NOT make me happy. |
| 62 | + Label.all.size.must_equal @iterations # <- any duplicated rows will NOT make me happy. |
| 63 | + end |
| 64 | +end |
0 commit comments