From e90e6e8f86e60d124a5319c12a193bc92b3fa6df Mon Sep 17 00:00:00 2001
From: Sam <sam.saffron@gmail.com>
Date: Thu, 16 May 2024 13:34:24 +1000
Subject: [PATCH] FIX: thread safety for active automation tracking (#27044)

---
 plugins/automation/plugin.rb                    |  4 ++--
 plugins/automation/spec/lib/triggerable_spec.rb | 14 ++++++++++++++
 2 files changed, 16 insertions(+), 2 deletions(-)

diff --git a/plugins/automation/plugin.rb b/plugins/automation/plugin.rb
index 9bd14646786..982d39c1dbd 100644
--- a/plugins/automation/plugin.rb
+++ b/plugins/automation/plugin.rb
@@ -30,11 +30,11 @@ module ::DiscourseAutomation
   USER_GROUP_MEMBERSHIP_THROUGH_BADGE_BULK_MODIFY_START_COUNT = 1000
 
   def self.set_active_automation(id)
-    @active_automation_id = id
+    Thread.current[:active_automation_id] = id
   end
 
   def self.get_active_automation
-    @active_automation_id
+    Thread.current[:active_automation_id]
   end
 end
 
diff --git a/plugins/automation/spec/lib/triggerable_spec.rb b/plugins/automation/spec/lib/triggerable_spec.rb
index 3065b428844..85f5ecb6aaf 100644
--- a/plugins/automation/spec/lib/triggerable_spec.rb
+++ b/plugins/automation/spec/lib/triggerable_spec.rb
@@ -16,6 +16,20 @@ describe DiscourseAutomation::Triggerable do
 
   fab!(:automation) { Fabricate(:automation, trigger: "foo") }
 
+  describe "active automation thread safety" do
+    after { DiscourseAutomation.set_active_automation(nil) }
+
+    it "ensurese thread safety when setting automation id" do
+      DiscourseAutomation.set_active_automation(10)
+
+      thread = Thread.new { DiscourseAutomation.get_active_automation }
+      thread.join
+      expect(thread.value).to eq(nil)
+
+      expect(DiscourseAutomation.get_active_automation).to eq(10)
+    end
+  end
+
   describe "#setting" do
     before { DiscourseAutomation::Triggerable.add("foo") { setting :bar, :baz } }