Skip to content

Commit

Permalink
Merge pull request #1102 from alphagov/fix-race-condition-in-statisti…
Browse files Browse the repository at this point in the history
…cs-creation

Fix race condition in petition statistics creation
  • Loading branch information
pixeltrix authored Dec 11, 2024
2 parents b716e62 + 6ed9ae5 commit 902c0da
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
2 changes: 2 additions & 0 deletions app/models/petition.rb
Original file line number Diff line number Diff line change
Expand Up @@ -510,6 +510,8 @@ def scheduled_debate_state

def statistics
super || create_statistics!
rescue ActiveRecord::RecordNotUnique => e
reload_statistics
end

def reset_signature_count!(time = Time.current)
Expand Down
23 changes: 23 additions & 0 deletions spec/models/petition_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4071,4 +4071,27 @@
end
end
end

describe "#statistics" do
let(:petition) { FactoryBot.create(:open_petition) }

it "creates a new statistics record if one doesn't exist" do
expect {
expect(petition.statistics).to be_an_instance_of(Petition::Statistics)
}.to change(Petition::Statistics, :count).by(1)
end

it "doesn't raise an ActiveRecord::RecordNotUnique error" do
expect {
p1 = described_class.find(petition.id)
p2 = described_class.find(petition.id)

expect(p1.association(:statistics).reader).to be_nil
expect(p1.association(:statistics)).to be_loaded

expect(p2.statistics).to be_an_instance_of(Petition::Statistics)
expect(p1.statistics).to eq(p2.statistics)
}.not_to raise_error
end
end
end

0 comments on commit 902c0da

Please sign in to comment.