2929from vulnerabilities .pipes .fetchcode_utils import get_versions
3030from vulnerabilities .pipes .group_advisories import group_advisory_for_package
3131from vulnerabilities .pipes .risk_score import compute_package_risk_score
32+ from vulnerabilities .pipes .risk_score import compute_package_risk_score_bulk
33+ from vulnerabilities .utils import TYPES_WITH_MULTIPLE_IMPORTERS
3234from vulnerabilities .utils import update_purl_version
3335
3436
@@ -164,7 +166,9 @@ def get_purl_versions(purl, cached_versions, logger):
164166
165167@transaction .atomic
166168def bulk_create_with_m2m (purls , impact , relation , logger ):
167- """Bulk create PackageV2 and also bulk populate M2M Impact and Package relationships."""
169+ """Bulk create PackageV2 and also bulk populate M2M Impact and Package relationships.
170+ This function assumes same base purl is used for all versions in ``purls`` list.
171+ """
168172 if not purls :
169173 return 0
170174
@@ -173,6 +177,31 @@ def bulk_create_with_m2m(purls, impact, relation, logger):
173177 if not affected_packages_v2 .exists ():
174178 return 0
175179
180+ affected_packages_v2 .first ().calculate_version_rank
181+
182+ if affected_packages_v2 .first ().type in TYPES_WITH_MULTIPLE_IMPORTERS :
183+ relations = group_advisories_for_package_with_lock (
184+ impact , affected_packages_v2 , relation , logger
185+ )
186+
187+ else :
188+ relations = [
189+ relation (impacted_package = impact , package = package ) for package in affected_packages_v2
190+ ]
191+
192+ try :
193+ relation .objects .bulk_create (relations , ignore_conflicts = True )
194+ except Exception as e :
195+ logger (f"Error creating ImpactedPackage { relation } : { e !r} \n { traceback_format_exc ()} " )
196+ return 0
197+
198+ compute_package_risk_score_bulk (affected_packages_v2 )
199+
200+ return len (relations )
201+
202+
203+ @transaction .atomic
204+ def group_advisories_for_package_with_lock (impact , affected_packages_v2 , relation , logger ):
176205 affected_packages_v2 = sorted (
177206 affected_packages_v2 ,
178207 key = lambda p : p .purl ,
@@ -214,14 +243,7 @@ def bulk_create_with_m2m(purls, impact, relation, logger):
214243 logger = logger ,
215244 )
216245
217- risk_score = compute_package_risk_score (pkg )
218-
219- logger (f"Computed risk score { risk_score } " f"for package { pkg .purl } " )
220-
221- pkg .risk_score = risk_score
222- pkg .save ()
223-
224- return len (relations )
246+ return relations
225247
226248
227249def impacted_package_qs (cutoff_day = 2 ):
0 commit comments