Reduce number of permission checks for subgroups in EpicsFinder
This is related to https://gitlab.com/gitlab-org/gitlab/-/issues/327106#note_549207150:
In EpicsFinder when we search for epics in many groups (typically when a group has many subgroups), then we have to check if user can read epics in each of this group. Because this is now done separately for each group (there is N+1 issue), we could optimize this by checking permissions only for subgroups which contain some epic (the idea is that not all subgroups will contain epics).
Before running user_can_read_groups, on all related groups, we could call something like groups.where(id: Epic.select(:group_id))
. We don't have to check every sub group permission if the group doesn't contain any epic.
This is quite simple change with big impact. This improvement should be significant for any bigger groups. For example for gitlab-org group in situations when a guest or anonymous user loads epics, we would check permissions for only 21 subgroups instead of 246 (this difference may be even higher as it doesn't include all sub-sub-groups
Update: a related comment is also in #327224 (comment 550166095) - INTERSECT
might be an option to use.