diff --git a/app/models/notification.rb b/app/models/notification.rb index 5c93072ea..2635bd487 100644 --- a/app/models/notification.rb +++ b/app/models/notification.rb @@ -136,6 +136,10 @@ class Notification < ApplicationRecord Notifications::UpdateJob.perform_later(notifiable.id, notifiable.class.name, action) end + def fast_destroy_old_notifications(destroy_before_timestamp = 4.months.ago) + Notification.where("created_at < ?", destroy_before_timestamp).in_batches(of: 10_000).delete_all + end + private def user_data(user) diff --git a/lib/tasks/fetch.rake b/lib/tasks/fetch.rake index a42f3d7e1..99b5e2821 100644 --- a/lib/tasks/fetch.rake +++ b/lib/tasks/fetch.rake @@ -37,8 +37,8 @@ task expire_old_listings: :environment do end end -task clear_memory_if_too_high: :environment do - Rails.cache.clear if Rails.cache.stats.flatten[1]["bytes"].to_i > 9_650_000_000 +task remove_old_notifications: :environment do + Notification.fast_destroy_old_notifications end task save_nil_hotness_scores: :environment do diff --git a/spec/factories/notifications.rb b/spec/factories/notifications.rb index d3a3c977a..35ae1b786 100644 --- a/spec/factories/notifications.rb +++ b/spec/factories/notifications.rb @@ -1,4 +1,7 @@ FactoryBot.define do factory :notification do + association :user, factory: :user, strategy: :create + association :organization, factory: :organization, strategy: :create + notifiable { create(:article) } end end diff --git a/spec/models/notification_spec.rb b/spec/models/notification_spec.rb index b0f426b48..e3ac9e96d 100644 --- a/spec/models/notification_spec.rb +++ b/spec/models/notification_spec.rb @@ -517,4 +517,17 @@ RSpec.describe Notification, type: :model do end end end + + describe "#fast_destroy_old_notifications" do + it "bulk deletes notifications older than 4 months by default" do + create_list :notification, 5 + described_class.last.update(created_at: 5.months.ago) + expect { described_class.fast_destroy_old_notifications }.to change(described_class, :count).by(-1) + end + + it "bulk deletes notifications older than a given timestamp" do + create_list :notification, 5 + expect { described_class.fast_destroy_old_notifications(Time.zone.now) }.to change(described_class, :count).by(-5) + end + end end