Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

2.3 KB
Raw Blame
from django.db import transaction
from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver

from posthog.exceptions_capture import capture_exception
from posthog.models import Team

from products.cohorts.backend.facade.ready_signals import connect_realtime_cohort_ready
from products.workflows.backend.models import HogFlow, HogFlowOptimization


def _sync_after_commit(team_id: int) -> None:
    def sync() -> None:
        # Deferred: the signals facade it pulls in would otherwise load on every django.setup().
        from products.workflows.backend.services import suggestions_scout  # noqa: PLC0415

        # Without a person there is nobody to grant the scout's write scope, so this can only switch it off.
        try:
            team = Team.objects.filter(id=team_id).select_related("parent_team").first()
            if team is not None:
                suggestions_scout.sync_suggestions_scout(team, acting_user=None, may_grant=False)
        except Exception as error:
            capture_exception(error)

    transaction.on_commit(sync)


@receiver(post_delete, sender=HogFlowOptimization)
def optimization_deleted(sender: type, instance: HogFlowOptimization, **kwargs: object) -> None:
    # Fires for each row a deleted workflow takes with it, in single and bulk deletes alike.
    if instance.enabled:
        _sync_after_commit(instance.team_id)


@receiver(post_save, sender=HogFlow)
def workflow_saved(sender: type, instance: HogFlow, **kwargs: object) -> None:
    # Archiving the last opted-in workflow has to stop the scout as surely as opting it out does.
    if (
        instance.status != HogFlow.State.ACTIVE
        and HogFlowOptimization.objects.unscoped().filter(hog_flow_id=instance.id, enabled=True).exists()
    ):
        _sync_after_commit(instance.team_id)


def _resume_runs_waiting_for_cohort(sender: object, *, team_id: int, cohort_id: int, **kwargs: object) -> None:
    from products.workflows.backend.tasks.batch_jobs import (  # noqa: PLC0415 — the task module imports the models this module loads
        resume_batch_jobs_waiting_for_realtime_cohort,
    )

    resume_batch_jobs_waiting_for_realtime_cohort.delay(team_id, cohort_id)


connect_realtime_cohort_ready(_resume_runs_waiting_for_cohort, dispatch_uid="workflows_resume_runs_waiting_for_cohort")