PERF: Avoid hitting DB when fetching draft sequence of bot user.

PERF: Avoid hitting DB when fetching draft sequence of bot user.

diff --git a/app/models/draft_sequence.rb b/app/models/draft_sequence.rb
index eeb5520..d77a6d4 100644
--- a/app/models/draft_sequence.rb
+++ b/app/models/draft_sequence.rb
@@ -23,6 +23,8 @@ class DraftSequence < ActiveRecord::Base
     user_id = user
     user_id = user.id unless user.is_a?(Integer)
 
+    return nil if user_id < 0
+
     # perf critical path
     r, _ = DB.query_single('select sequence from draft_sequences where user_id = ? and draft_key = ?', user_id, key)
     r.to_i
diff --git a/spec/models/draft_sequence_spec.rb b/spec/models/draft_sequence_spec.rb
index 5147f46..282b129 100644
--- a/spec/models/draft_sequence_spec.rb
+++ b/spec/models/draft_sequence_spec.rb
@@ -5,9 +5,16 @@ require 'rails_helper'
 describe DraftSequence do
   fab!(:user) { Fabricate(:user) }
 
-  it 'should produce next sequence for a key' do
-    expect(DraftSequence.next!(user, 'test')).to eq 1
-    expect(DraftSequence.next!(user, 'test')).to eq 2
+  describe '.next' do
+    it 'should produce next sequence for a key' do
+      expect(DraftSequence.next!(user, 'test')).to eq 1
+      expect(DraftSequence.next!(user, 'test')).to eq 2
+    end
+
+    it 'should not produce next sequence for non-human user' do
+      user.id = -99999
+      2.times { expect(DraftSequence.next!(user, 'test')).to eq(0) }
+    end
   end
 
   describe '.current' do
@@ -15,6 +22,11 @@ describe DraftSequence do
       expect(DraftSequence.current(user, 'test')).to eq 0
     end
 
+    it 'should return nil for non-human user' do
+      user.id = -99999
+      expect(DraftSequence.current(user, 'test')).to eq(nil)
+    end
+
     it 'should return the right sequence' do
       expect(DraftSequence.next!(user, 'test')).to eq(1)
       expect(DraftSequence.current(user, 'test')).to eq(1)

GitHub sha: d301af39

2 Likes

This commit has been mentioned on Discourse Meta. There might be relevant details there:

https://meta.discourse.org/t/using-the-zapier-discourse-zap-templates/121603/5