PERF: limit unread count to 99 in the blue circle

This safeguard is in place to avoid very expensive queries on the server
side
This commit is contained in:
Sam 2018-10-24 11:53:28 +11:00
parent 29fdb50338
commit e605542c4e

View File

@ -434,24 +434,31 @@ class User < ActiveRecord::Base
@unread_pms ||= unread_notifications_of_type(Notification.types[:private_message]) @unread_pms ||= unread_notifications_of_type(Notification.types[:private_message])
end end
# PERF: This safeguard is in place to avoid situations where
# a user with enormous amounts of unread data can issue extremely
# expensive queries
MAX_UNREAD_NOTIFICATIONS = 99
def unread_notifications def unread_notifications
@unread_notifications ||= begin @unread_notifications ||= begin
# perf critical, much more efficient than AR # perf critical, much more efficient than AR
sql = <<~SQL sql = <<~SQL
SELECT COUNT(*) SELECT COUNT(*) FROM notifications n
FROM notifications n
LEFT JOIN topics t ON t.id = n.topic_id LEFT JOIN topics t ON t.id = n.topic_id
WHERE t.deleted_at IS NULL WHERE t.deleted_at IS NULL AND
AND n.notification_type <> :pm n.notification_type <> :pm AND
AND n.user_id = :user_id n.user_id = :user_id AND
AND n.id > :seen_notification_id n.id > :seen_notification_id AND
AND NOT read NOT read
LIMIT :limit
SQL SQL
DB.query_single(sql, DB.query_single(sql,
user_id: id, user_id: id,
seen_notification_id: seen_notification_id, seen_notification_id: seen_notification_id,
pm: Notification.types[:private_message] pm: Notification.types[:private_message],
limit: MAX_UNREAD_NOTIFICATIONS
)[0].to_i )[0].to_i
end end
end end