DEV: ensure rebaking works even when some users have inconsistent data (#30261)

* DEV: add db consistency check for UserEmail

* DEV: add db consistency check for UserAvatar

* DEV: ignore inconsistent data related to user avatars when deciding whether to rebake old posts


Co-authored-by: Alan Guo Xiang Tan <gxtan1990@gmail.com>

---------

Co-authored-by: Alan Guo Xiang Tan <gxtan1990@gmail.com>
This commit is contained in:
Kelv
2024-12-16 19:48:25 +08:00
committed by GitHub
parent ce8c2ef6d9
commit 04ba5baec0
7 changed files with 118 additions and 2 deletions

View File

@@ -152,6 +152,13 @@ class UserAvatar < ActiveRecord::Base
end
def self.ensure_consistency!(max_optimized_avatars_to_remove: 20_000)
DB.exec <<~SQL
DELETE FROM user_avatars
USING user_avatars ua
LEFT JOIN users u ON ua.user_id = u.id
WHERE user_avatars.id = ua.id AND u.id IS NULL
SQL
DB.exec <<~SQL
UPDATE user_avatars
SET gravatar_upload_id = NULL

View File

@@ -22,6 +22,23 @@ class UserEmail < ActiveRecord::Base
before_save -> { destroy_email_tokens(self.email_was) }, if: :will_save_change_to_email?
after_destroy { destroy_email_tokens(self.email) }
def self.ensure_consistency!
user_ids_without_primary_email = DB.query_single <<~SQL
SELECT u.id
FROM users u
LEFT JOIN user_emails ue ON u.id = ue.user_id AND ue.primary = true
WHERE ue.id IS NULL;
SQL
user_ids_without_primary_email.each do |user_id|
UserEmail.create!(
user_id: user_id,
# 64 max character length of local-part for the email address https://datatracker.ietf.org/doc/html/rfc5321#section-4.5.3.1.1
email: "#{SecureRandom.alphanumeric(64)}@missing-primary-email.invalid",
primary: true,
)
end
end
def normalize_email
self.normalized_email =