|
| 1 | +from typing import Any |
| 2 | + |
| 3 | +import structlog |
| 4 | +from django.core.cache import cache |
| 5 | +from django.db.models.signals import pre_save |
| 6 | +from django.dispatch import receiver |
| 7 | + |
| 8 | +from api.models.Collaborative import Collaborative |
| 9 | +from api.utils.enums import CollaborativeStatus |
| 10 | +from search.documents import CollaborativeDocument |
| 11 | + |
| 12 | +from .dataset_signals import SEARCH_CACHE_VERSION_KEY |
| 13 | + |
| 14 | +logger = structlog.get_logger(__name__) |
| 15 | + |
| 16 | + |
| 17 | +@receiver(pre_save, sender=Collaborative) |
| 18 | +def handle_collaborative_publication(sender: Any, instance: Collaborative, **kwargs: Any) -> None: |
| 19 | + """Sync Elasticsearch index when collaborative publication state changes.""" |
| 20 | + |
| 21 | + try: |
| 22 | + if not instance.pk: |
| 23 | + return |
| 24 | + |
| 25 | + original = Collaborative.objects.get(pk=instance.pk) |
| 26 | + |
| 27 | + status_changing_to_published = ( |
| 28 | + original.status != CollaborativeStatus.PUBLISHED |
| 29 | + and instance.status == CollaborativeStatus.PUBLISHED |
| 30 | + ) |
| 31 | + status_changing_from_published = ( |
| 32 | + original.status == CollaborativeStatus.PUBLISHED |
| 33 | + and instance.status != CollaborativeStatus.PUBLISHED |
| 34 | + ) |
| 35 | + remains_published = ( |
| 36 | + original.status == CollaborativeStatus.PUBLISHED |
| 37 | + and instance.status == CollaborativeStatus.PUBLISHED |
| 38 | + ) |
| 39 | + |
| 40 | + if status_changing_to_published or status_changing_from_published: |
| 41 | + version = cache.get(SEARCH_CACHE_VERSION_KEY, 0) |
| 42 | + cache.set(SEARCH_CACHE_VERSION_KEY, version + 1) |
| 43 | + logger.info("Invalidated search cache for collaborative", collaborative_id=instance.id) |
| 44 | + |
| 45 | + if status_changing_from_published: |
| 46 | + document = CollaborativeDocument.get(id=instance.id, ignore=404) |
| 47 | + if document: |
| 48 | + document.delete() |
| 49 | + logger.info( |
| 50 | + "Removed collaborative from Elasticsearch index", |
| 51 | + collaborative_id=instance.id, |
| 52 | + ) |
| 53 | + elif status_changing_to_published or remains_published: |
| 54 | + document = CollaborativeDocument.get(id=instance.id, ignore=404) |
| 55 | + if document: |
| 56 | + document.update(instance) |
| 57 | + else: |
| 58 | + CollaborativeDocument().update(instance) |
| 59 | + logger.info( |
| 60 | + "Synced collaborative to Elasticsearch index", |
| 61 | + collaborative_id=instance.id, |
| 62 | + ) |
| 63 | + |
| 64 | + except Exception as exc: # pragma: no cover - logging only |
| 65 | + logger.error( |
| 66 | + "Error in collaborative publication signal handler", |
| 67 | + collaborative_id=getattr(instance, "id", None), |
| 68 | + error=str(exc), |
| 69 | + ) |
| 70 | + # Avoid raising to prevent save failures |
0 commit comments