Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

ensure thread safety of journal notifications

ulferts79409370ee4e
diff --git a/app/models/journal/notification_configuration.rb b/app/models/journal/notification_configuration.rb
index 5b48b8e3dcd..bc4576c5732 100644
--- a/app/models/journal/notification_configuration.rb
+++ b/app/models/journal/notification_configuration.rb
@@ -36,7 +36,7 @@ class Journal::NotificationConfiguration
# This allows to control the setting globally without having to pass the setting down the call stack in
# order to ensure all subsequent code follows the provided setting.
def with(send_notifications, &block)
- if already_set
+ if already_set?
log_warning(send_notifications)
yield
else
@@ -45,13 +45,13 @@ class Journal::NotificationConfiguration
end
def active?
- active
+ active.value
end
protected
def with_first(send_notifications)
- old_value = active
+ old_value = active?
self.already_set = true
self.active = send_notifications
@@ -71,10 +71,24 @@ class Journal::NotificationConfiguration
Rails.logger.debug message
end
- attr_accessor :active,
- :already_set
- end
+ def active
+ @active ||= Concurrent::ThreadLocalVar.new(true)
+ end
+
+ def already_set
+ @already_set ||= Concurrent::ThreadLocalVar.new(false)
+ end
+
+ def already_set?
+ already_set.value
+ end
+
+ def active=(value)
+ @active.value = value
+ end
- self.active = true
- self.already_set = false
+ def already_set=(value)
+ @already_set.value = value
+ end
+ end
end
diff --git a/spec/models/journal/notification_configuration_spec.rb b/spec/models/journal/notification_configuration_spec.rb
index 73282660a94..bae6084ef9d 100644
--- a/spec/models/journal/notification_configuration_spec.rb
+++ b/spec/models/journal/notification_configuration_spec.rb
@@ -69,6 +69,23 @@ describe Journal::NotificationConfiguration, type: :model do
.to eql !send_notification_before
end
+ it 'is thread safe' do
+ thread = Thread.new do
+ described_class.with true do
+ inner = Thread.new do
+ described_class.with false do
+ Journal::NotificationConfiguration.active?
+ end
+ end
+
+ [Journal::NotificationConfiguration.active?, inner.value]
+ end
+ end
+
+ expect(thread.value)
+ .to eql [true, false]
+ end
+
context 'with an exception being raised within the block' do
it 'raises the exception but always resets the notification value' do
expect { described_class.with(!send_notification_before) { raise ArgumentError } }