Skip to content

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

FIX: Avoid chat retention timeouts when deleting large mentions (#44156)

Natalie Tay9fc94d9d09c6
diff --git a/plugins/chat/app/models/chat/mention.rb b/plugins/chat/app/models/chat/mention.rb
index c49d24444fd..3764800506e 100644
--- a/plugins/chat/app/models/chat/mention.rb
+++ b/plugins/chat/app/models/chat/mention.rb
@@ -8,7 +8,20 @@ module Chat
has_many :mention_notifications,
class_name: "Chat::MentionNotification",
foreign_key: :chat_mention_id
- has_many :notifications, through: :mention_notifications, dependent: :destroy
+ has_many :notifications, through: :mention_notifications
+
+ before_destroy :destroy_notifications
+
+ private
+
+ def destroy_notifications
+ links = Chat::MentionNotification.where(chat_mention_id: id)
+
+ # Destroying the through association repeatedly scans its loaded join records.
+ Notification.where(id: links.select(:notification_id)).find_each(batch_size: 200, &:destroy!)
+
+ links.delete_all
+ end
end
end
diff --git a/plugins/chat/spec/models/chat/mention_spec.rb b/plugins/chat/spec/models/chat/mention_spec.rb
new file mode 100644
index 00000000000..9adb0c59e8d
--- /dev/null
+++ b/plugins/chat/spec/models/chat/mention_spec.rb
@@ -0,0 +1,25 @@
+# frozen_string_literal: true
+
+describe Chat::Mention do
+ describe "#destroy!" do
+ it "destroys related notifications and join records while preserving unrelated ones" do
+ mention = Fabricate(:all_chat_mention)
+ first_link = Fabricate(:chat_mention_notification, chat_mention: mention)
+ second_link = Fabricate(:chat_mention_notification, chat_mention: mention)
+ other_link = Fabricate(:chat_mention_notification)
+ notification_ids = [first_link.notification_id, second_link.notification_id]
+
+ mention.destroy!
+
+ expect(Notification.where(id: notification_ids)).not_to exist
+ expect(Chat::MentionNotification.where(chat_mention_id: mention.id)).not_to exist
+ expect(
+ Chat::MentionNotification.where(
+ chat_mention_id: other_link.chat_mention_id,
+ notification_id: other_link.notification_id,
+ ),
+ ).to exist
+ expect(other_link.notification.reload).to be_present
+ end
+ end
+end