Skip to content

A platform for community discussion. Free, open, simple.

FIX: Catch possible PG exception from `Chat::AutoJoinChannels` (#34132)

Loïc Guitauteb0973339164
diff --git a/plugins/chat/app/services/chat/auto_join_channels.rb b/plugins/chat/app/services/chat/auto_join_channels.rb
index 7b391627f13..e84c52e7481 100644
--- a/plugins/chat/app/services/chat/auto_join_channels.rb
+++ b/plugins/chat/app/services/chat/auto_join_channels.rb
@@ -17,7 +17,9 @@ module Chat
attribute :category_id, :integer
end
- step :create_memberships
+ lock(:user_id, :channel_id, :category_id) do
+ try(PG::UniqueViolation) { step :create_memberships }
+ end
private
diff --git a/plugins/chat/plugin.rb b/plugins/chat/plugin.rb
index 7a5834e1150..4f26c38d864 100644
--- a/plugins/chat/plugin.rb
+++ b/plugins/chat/plugin.rb
@@ -339,8 +339,14 @@ after_initialize do
Chat::AutoJoinChannels.call(params: { user_id: user.id }) if user.active?
end
- on(:user_added_to_group) do |user, _group|
- Chat::AutoJoinChannels.call(params: { user_id: user.id })
+ on(:user_added_to_group) do |user, group|
+ Chat::AutoJoinChannels.call(params: { user_id: user.id }) do |result|
+ on_exceptions do |exception|
+ Rails.logger.warn(
+ "[chat] Error auto-joining user #{user.id} to channels after being added to group #{group.id}: #{exception.message}\n\n#{result.inspect_steps}",
+ )
+ end
+ end
end
on(:user_removed_from_group) do |user, _group|
diff --git a/plugins/chat/spec/services/chat/auto_join_channels_spec.rb b/plugins/chat/spec/services/chat/auto_join_channels_spec.rb
index 35baa98ca12..3ce3923d81c 100644
--- a/plugins/chat/spec/services/chat/auto_join_channels_spec.rb
+++ b/plugins/chat/spec/services/chat/auto_join_channels_spec.rb
@@ -15,6 +15,12 @@ RSpec.describe Chat::AutoJoinChannels do
it { is_expected.to fail_a_policy(:chat_enabled?) }
end
+ context "when a duplicate key error occurs" do
+ before { allow(DB).to receive(:query_array).and_raise(PG::UniqueViolation) }
+
+ it { is_expected.to fail_with_exception(PG::UniqueViolation) }
+ end
+
context "when chat is enabled" do
let(:trust_level) { 1 } # SiteSetting.chat_allowed_groups defaults to admins, moderators, and TL1 users
let(:last_seen_at) { 5.minutes.ago } # Users must have been seen "recently" to be auto-joined to a channel