Coverage for backend/django/core/auxiliary/signals.py: 86%

27 statements  

« prev     ^ index     » next       coverage.py v7.10.7, created at 2026-05-13 02:47 +0000

1import logging 

2 

3from botocore.exceptions import ClientError 

4from django.db.models.signals import post_delete 

5from django.dispatch import receiver 

6 

7from core.auxiliary.models.MLModel import MLModel 

8from core.auxiliary.models.UploadSession import UploadSession 

9from core.auxiliary.services.csv_lifecycle import SHORT_CSV_LIFECYCLE_TTL, expires_at_from_ttl 

10from core.auxiliary.services.object_storage.s3 import schedule_object_expiration 

11 

12 

13logger = logging.getLogger(__name__) 

14 

15 

16def _shorten_csv_lifecycle(*, bucket: str, key: str) -> None: 

17 """Best-effort lifecycle shortening for storage objects referenced by deleted rows.""" 

18 try: 

19 schedule_object_expiration( 

20 bucket=bucket, 

21 key=key, 

22 expires_at=expires_at_from_ttl(SHORT_CSV_LIFECYCLE_TTL), 

23 ) 

24 except ClientError as exc: 

25 error_code = exc.response.get("Error", {}).get("Code") 

26 if error_code != "NoSuchBucket": 26 ↛ 27line 26 didn't jump to line 27 because the condition on line 26 was never true

27 raise 

28 

29 logger.warning( 

30 "Skipping CSV lifecycle shortening because bucket %s no longer exists.", 

31 bucket, 

32 extra={"bucket": bucket, "object_key": key}, 

33 ) 

34 

35 

36@receiver(post_delete, sender=UploadSession) 

37def shorten_upload_session_csv_lifecycle_on_delete(sender, instance: UploadSession, **kwargs) -> None: 

38 if not instance.bucket or not instance.object_key: 38 ↛ 39line 38 didn't jump to line 39 because the condition on line 38 was never true

39 return 

40 

41 _shorten_csv_lifecycle(bucket=instance.bucket, key=instance.object_key) 

42 

43 

44@receiver(post_delete, sender=MLModel) 

45def shorten_ml_results_lifecycle_on_delete(sender, instance: MLModel, **kwargs) -> None: 

46 for bucket, key in ( 

47 (instance.csv_bucket, instance.csv_object_key), 

48 (instance.test_results_bucket, instance.test_results_key), 

49 ): 

50 if bucket and key: 50 ↛ 46line 50 didn't jump to line 46 because the condition on line 50 was always true

51 _shorten_csv_lifecycle(bucket=bucket, key=key)