: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(messaging): move the opt-out API behind the facade (#113996)
Harley Alexanderb649be01e76c
diff --git a/products/messaging/backend/facade/preferences.py b/products/messaging/backend/facade/preferences.pynew file mode 100644index 000000000000..a8292d777a69--- /dev/null+++ b/products/messaging/backend/facade/preferences.py@@ -0,0 +1,108 @@+"""Recipient opt-outs: who opted out of which message category, and changes to that list."""++from collections.abc import Iterator, Sequence+from datetime import datetime+from typing import Any+from uuid import UUID++from posthog.dataclasses import frozen++from products.messaging.backend.models.message_preferences import MessageRecipientPreference+from products.messaging.backend.services import preferences as preferences_service+from products.messaging.backend.services.lazy_list import LazyList+from products.messaging.backend.services.opt_out_service import BulkOptOutEntry, UnknownCategoryError+++class MessageCategoryNotFound(Exception):+ """No category with the requested key exists for the team. The message names the key when known."""+++@frozen+class RecipientPreferences:+ id: UUID+ identifier: str+ updated_at: datetime+ # Category id (or the reserved `$all` key) to OPTED_IN, OPTED_OUT or NO_PREFERENCE.+ preferences: dict[str, Any]+++@frozen+class ChangedPreferences:+ preferences: RecipientPreferences+ created: bool+++@frozen+class OptOutRequest:+ identifier: str+ category_key: str | None = None+++@frozen+class BulkOptOutOutcome:+ total: int+ opted_out: int+ skipped: int+ errors: list[str]+++def _to_contract(row: MessageRecipientPreference) -> RecipientPreferences:+ return RecipientPreferences(+ id=row.id, identifier=row.identifier, updated_at=row.updated_at, preferences=row.preferences+ )+++def list_opt_outs(team_id: int, category_key: str | None, search: str | None) -> Sequence[RecipientPreferences]:+ """Recipients opted out of the category, or of all marketing when no key is given. Most recent first.++ Sizing is a COUNT, and a slice reads one page. Raises MessageCategoryNotFound for an unknown key.+ """+ try:+ rows = preferences_service.opted_out(team_id, category_key, search)+ except preferences_service.CategoryNotFound as e:+ raise MessageCategoryNotFound("Category not found") from e+ return LazyList(rows, _to_contract)+++def add_opt_out(+ team_id: int, identifier: str, category_key: str | None, created_by_id: int | None+) -> ChangedPreferences:+ """Opt the recipient out of the category, or of all marketing. Syncs to Customer.io after commit."""+ try:+ row, created = preferences_service.add_opt_out(team_id, identifier, category_key, created_by_id)+ except preferences_service.CategoryNotFound as e:+ raise MessageCategoryNotFound("Category not found") from e+ return ChangedPreferences(preferences=_to_contract(row), created=created)+++def remove_opt_out(+ team_id: int, identifier: str, category_key: str | None, created_by_id: int | None+) -> ChangedPreferences:+ """Opt the recipient back in, lifting a global opt-out without widening it. Syncs after commit."""+ try:+ row, created = preferences_service.remove_opt_out(team_id, identifier, category_key, created_by_id)+ except preferences_service.CategoryNotFound as e:+ raise MessageCategoryNotFound("Category not found") from e+ return ChangedPreferences(preferences=_to_contract(row), created=created)+++def export_opt_outs_csv(team_id: int, category_key: str | None) -> Iterator[str]:+ """CSV rows of the opt-out list, in the format the CSV import reads back."""+ try:+ return preferences_service.export_rows(team_id, category_key)+ except UnknownCategoryError as e:+ raise MessageCategoryNotFound(str(e)) from e+++def bulk_opt_out(+ team_id: int, requests: list[OptOutRequest], default_category_key: str | None, created_by_id: int | None+) -> BulkOptOutOutcome:+ """Opt every recipient out of its own category, or the default one. Unknown categories are skipped."""+ entries = [BulkOptOutEntry(identifier=r.identifier, category_key=r.category_key) for r in requests]+ try:+ result = preferences_service.bulk_opt_out(team_id, entries, default_category_key, created_by_id)+ except UnknownCategoryError as e:+ raise MessageCategoryNotFound(str(e)) from e+ return BulkOptOutOutcome(+ total=result.total, opted_out=result.opted_out, skipped=result.skipped, errors=result.errors+ )diff --git a/products/messaging/backend/presentation/views/message_preferences.py b/products/messaging/backend/presentation/views/message_preferences.pyindex 5cc1264d63f2..152288b40bbe 100644--- a/products/messaging/backend/presentation/views/message_preferences.py+++ b/products/messaging/backend/presentation/views/message_preferences.py@@ -1,8 +1,6 @@import refrom typing import Any, Literal-from django.db import transaction-from drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schemafrom rest_framework import serializers, status, viewsets@@ -18,14 +16,16 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.streaming import streaming_responsefrom posthog.plugins import plugin_server_api-from products.messaging.backend.models.message_category import MessageCategory, MessageCategoryType-from products.messaging.backend.models.message_preferences import (- ALL_MESSAGE_PREFERENCE_CATEGORY_ID,- MessageRecipientPreference,- PreferenceStatus,+from products.messaging.backend.facade.preferences import (+ MessageCategoryNotFound,+ OptOutRequest,+ RecipientPreferences,+ add_opt_out,+ bulk_opt_out,+ export_opt_outs_csv,+ list_opt_outs,+ remove_opt_out,)-from products.messaging.backend.services.opt_out_service import BulkOptOutEntry, OptOutService, UnknownCategoryError-from products.messaging.backend.tasks import sync_preferences_to_customerio_taskMAX_BULK_OPT_OUT_ENTRIES = 1000UNSAFE_FILENAME_CHARACTERS = re.compile(r"[^A-Za-z0-9_-]+")@@ -37,7 +37,8 @@ class OptOutsPagination(PageNumberPagination):max_page_size = 100-class MessagePreferencesSerializer(serializers.ModelSerializer):+class MessagePreferencesSerializer(serializers.Serializer):+ id = serializers.UUIDField(read_only=True, help_text="Server-assigned UUID for this recipient's preference record.")identifier = serializers.CharField(help_text="The recipient identifier (e.g. email address).")updated_at = serializers.DateTimeField(help_text="When the preference was last updated.")preferences = serializers.JSONField(@@ -45,25 +46,6 @@ class MessagePreferencesSerializer(serializers.ModelSerializer):"The reserved `$all` key covers every marketing message.")- class Meta:- model = MessageRecipientPreference- fields = [- "id",- "identifier",- "updated_at",- "preferences",- ]- read_only_fields = [- "id",- "identifier",- "created_at",- "updated_at",- "created_by",- ]- extra_kwargs = {- "id": {"help_text": "Server-assigned UUID for this recipient's preference record."},- }-class AddOptOutRequestSerializer(serializers.Serializer):identifier = serializers.CharField(@@ -221,30 +203,19 @@ class MessagePreferencesViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):"""Get opt-outs filtered by category or overall opt-outs if no category specified"""self._require_resource_access("viewer", "You need hog_flow viewer access to view the opt-out list.")- category_key = request.validated_query_data.get("category_key")-- # Find recipients who have opted out of this specific category, or use the derived $all category if no specific category is provided- preference_key = ALL_MESSAGE_PREFERENCE_CATEGORY_ID- if category_key:- category = MessageCategory.objects.filter(key=category_key, team_id=self.team_id).first()- if category is None:- return Response({"error": "Category not found"}, status=404)- preference_key = str(category.id)-- opt_outs = MessageRecipientPreference.objects.filter(- team_id=self.team_id,- **{f"preferences__{preference_key}": PreferenceStatus.OPTED_OUT.value},- )-- search = request.validated_query_data.get("search")- if search:- opt_outs = opt_outs.filter(identifier__icontains=search)-- opt_outs = opt_outs.order_by("-updated_at") # Order by most recently updated first+ try:+ opt_outs = list_opt_outs(+ self.team_id,+ request.validated_query_data.get("category_key"),+ request.validated_query_data.get("search"),+ )+ except MessageCategoryNotFound:+ return Response({"error": "Category not found"}, status=404)# Apply paginationpaginator = OptOutsPagination()- page = paginator.paginate_queryset(opt_outs, request)+ # The paginator only needs len() and slicing, which the facade's sequence provides.+ page: list[RecipientPreferences] | None = paginator.paginate_queryset(opt_outs, request) # type: ignore[arg-type]if page is not None:serializer = MessagePreferencesSerializer(page, many=True)return paginator.get_paginated_response(serializer.data)@@ -269,27 +240,13 @@ class MessagePreferencesViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):identifier = serializer.validated_data["identifier"]category_key = serializer.validated_data.get("category_key")- category = None- if category_key:- category = MessageCategory.objects.filter(key=category_key, team_id=self.team_id).first()- if category is None:- return Response({"error": "Category not found"}, status=status.HTTP_404_NOT_FOUND)-- category_id = str(category.id) if category else ALL_MESSAGE_PREFERENCE_CATEGORY_ID-- preference, created = MessageRecipientPreference.objects.get_or_create(- team_id=self.team_id,- identifier=identifier,- defaults={"created_by": request.user},- )- preference.set_preference(category_id, PreferenceStatus.OPTED_OUT)-- # Customer.io round-trips can take tens of seconds, so sync off the request path- # once the preference write has committed.- transaction.on_commit(lambda: sync_preferences_to_customerio_task.delay(self.team_id, identifier))+ try:+ changed = add_opt_out(self.team_id, identifier, category_key, request.user.id)+ except MessageCategoryNotFound:+ return Response({"error": "Category not found"}, status=status.HTTP_404_NOT_FOUND)- response_status = status.HTTP_201_CREATED if created else status.HTTP_200_OK- return Response(MessagePreferencesSerializer(preference).data, status=response_status)+ response_status = status.HTTP_201_CREATED if changed.created else status.HTTP_200_OK+ return Response(MessagePreferencesSerializer(changed.preferences).data, status=response_status)@extend_schema(request=RemoveOptOutRequestSerializer,@@ -307,62 +264,13 @@ class MessagePreferencesViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):identifier = serializer.validated_data["identifier"]category_key = serializer.validated_data.get("category_key")- category = None- if category_key:- category = MessageCategory.objects.filter(key=category_key, team_id=self.team_id).first()- if category is None:- return Response({"error": "Category not found"}, status=status.HTTP_404_NOT_FOUND)-- preference, created = MessageRecipientPreference.objects.get_or_create(- team_id=self.team_id,- identifier=identifier,- defaults={"created_by": request.user},- )- preferences = dict(preference.preferences or {})-- if category is None:- preferences[ALL_MESSAGE_PREFERENCE_CATEGORY_ID] = PreferenceStatus.OPTED_IN.value- else:- self._lift_global_opt_out(preferences, category)- preferences[str(category.id)] = PreferenceStatus.OPTED_IN.value-- preference.preferences = preferences- preference.save(update_fields=["preferences", "updated_at"])-- transaction.on_commit(lambda: sync_preferences_to_customerio_task.delay(self.team_id, identifier))-- response_status = status.HTTP_201_CREATED if created else status.HTTP_200_OK- return Response(MessagePreferencesSerializer(preference).data, status=response_status)-- def _lift_global_opt_out(self, preferences: dict[str, Any], category: MessageCategory) -> None:- """Clear a `$all` opt-out that would otherwise swallow a per-category resubscribe.-- Sends check the category and `$all` together, so opting someone back in to one category- does nothing while `$all` stays opted out. Pin the team's other marketing categories to- opted out first, so lifting `$all` resubscribes only the category the caller named- instead of silently widening consent to everything.-- The pinning overwrites even an explicit OPTED_IN on a sibling category (e.g. one a- Customer.io webhook recorded): while `$all` was opted out that opt-in was inert, so- preserving the recipient's effective state means opting the sibling out, not letting- the stale opt-in spring back to life.- """- if category.category_type != MessageCategoryType.MARKETING:- return- if preferences.get(ALL_MESSAGE_PREFERENCE_CATEGORY_ID) != PreferenceStatus.OPTED_OUT.value:- return-- other_category_ids = (- MessageCategory.objects.filter(- team_id=self.team_id, category_type=MessageCategoryType.MARKETING, deleted=False- )- .exclude(id=category.id)- .values_list("id", flat=True)- )- for other_category_id in other_category_ids:- preferences[str(other_category_id)] = PreferenceStatus.OPTED_OUT.value+ try:+ changed = remove_opt_out(self.team_id, identifier, category_key, request.user.id)+ except MessageCategoryNotFound:+ return Response({"error": "Category not found"}, status=status.HTTP_404_NOT_FOUND)- preferences[ALL_MESSAGE_PREFERENCE_CATEGORY_ID] = PreferenceStatus.OPTED_IN.value+ response_status = status.HTTP_201_CREATED if changed.created else status.HTTP_200_OK+ return Response(MessagePreferencesSerializer(changed.preferences).data, status=response_status)@extend_schema(parameters=[@@ -386,11 +294,9 @@ class MessagePreferencesViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):self._require_resource_access("viewer", "You need hog_flow viewer access to view the opt-out list.")category_key = request.query_params.get("category_key")- service = OptOutService(team_id=self.team_id, user=request.user)-try:- rows = service.export_rows(category_key)- except UnknownCategoryError as e:+ rows = export_opt_outs_csv(self.team_id, category_key)+ except MessageCategoryNotFound as e:return Response({"error": str(e)}, status=status.HTTP_404_NOT_FOUND)filename_suffix = (@@ -418,15 +324,16 @@ class MessagePreferencesViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):serializer = BulkAddOptOutsRequestSerializer(data=request.data)serializer.is_valid(raise_exception=True)- entries = [- BulkOptOutEntry(identifier=entry["identifier"], category_key=entry.get("category_key") or None)+ requests = [+ OptOutRequest(identifier=entry["identifier"], category_key=entry.get("category_key") or None)for entry in serializer.validated_data["opt_outs"]]- service = OptOutService(team_id=self.team_id, user=request.user)try:- result = service.opt_out_recipients(entries, serializer.validated_data.get("category_key") or None)- except UnknownCategoryError as e:+ result = bulk_opt_out(+ self.team_id, requests, serializer.validated_data.get("category_key") or None, request.user.id+ )+ except MessageCategoryNotFound as e:return Response({"error": str(e)}, status=status.HTTP_404_NOT_FOUND)return Response(BulkAddOptOutsResultSerializer(result).data, status=status.HTTP_200_OK)diff --git a/products/messaging/backend/services/opt_out_service.py b/products/messaging/backend/services/opt_out_service.pyindex 05151d95ed6a..629cf635e816 100644--- a/products/messaging/backend/services/opt_out_service.py+++ b/products/messaging/backend/services/opt_out_service.py@@ -54,9 +54,9 @@ class _Echo:class OptOutService:"""Reads and writes opt-out lists in bulk, so recipients can be moved in and out of PostHog."""- def __init__(self, team_id: int, user: Optional[Any] = None):+ def __init__(self, team_id: int, created_by_id: Optional[int] = None):self.team_id = team_id- self.user = user+ self.created_by_id = created_by_iddef _category_key_to_id(self) -> dict[str, str]:"""Map every usable category key to the ID stored in a recipient's preferences blob."""@@ -187,7 +187,7 @@ class OptOutService:MessageRecipientPreference(team_id=self.team_id,identifier=identifier,- created_by=self.user,+ created_by_id=self.created_by_id,preferences=dict.fromkeys(category_ids, PreferenceStatus.OPTED_OUT.value),))diff --git a/products/messaging/backend/services/preferences.py b/products/messaging/backend/services/preferences.pynew file mode 100644index 000000000000..b45860dd6e7e--- /dev/null+++ b/products/messaging/backend/services/preferences.py@@ -0,0 +1,125 @@+from collections.abc import Iterator+from typing import Any++from django.db import transaction+from django.db.models import QuerySet++from products.messaging.backend.models.message_category import MessageCategory, MessageCategoryType+from products.messaging.backend.models.message_preferences import (+ ALL_MESSAGE_PREFERENCE_CATEGORY_ID,+ MessageRecipientPreference,+ PreferenceStatus,+)+from products.messaging.backend.services.opt_out_service import BulkOptOutEntry, BulkOptOutResult, OptOutService+from products.messaging.backend.tasks import sync_preferences_to_customerio_task+++class CategoryNotFound(Exception):+ pass+++def _category(team_id: int, category_key: str) -> MessageCategory:+ category = MessageCategory.objects.filter(key=category_key, team_id=team_id).first()+ if category is None:+ raise CategoryNotFound()+ return category+++def opted_out(team_id: int, category_key: str | None, search: str | None) -> QuerySet[MessageRecipientPreference]:+ # Find recipients who have opted out of this specific category, or use the derived $all category if no specific category is provided+ preference_key = str(_category(team_id, category_key).id) if category_key else ALL_MESSAGE_PREFERENCE_CATEGORY_ID++ opt_outs = MessageRecipientPreference.objects.filter(+ team_id=team_id,+ **{f"preferences__{preference_key}": PreferenceStatus.OPTED_OUT.value},+ )+ if search:+ opt_outs = opt_outs.filter(identifier__icontains=search)+ return opt_outs.order_by("-updated_at") # Order by most recently updated first+++def _sync_after_commit(team_id: int, identifier: str) -> None:+ # Customer.io round-trips can take tens of seconds, so sync off the request path+ # once the preference write has committed.+ transaction.on_commit(lambda: sync_preferences_to_customerio_task.delay(team_id, identifier))+++def add_opt_out(+ team_id: int, identifier: str, category_key: str | None, created_by_id: int | None+) -> tuple[MessageRecipientPreference, bool]:+ category = _category(team_id, category_key) if category_key else None+ category_id = str(category.id) if category else ALL_MESSAGE_PREFERENCE_CATEGORY_ID++ preference, created = MessageRecipientPreference.objects.get_or_create(+ team_id=team_id,+ identifier=identifier,+ defaults={"created_by_id": created_by_id},+ )+ preference.set_preference(category_id, PreferenceStatus.OPTED_OUT)++ _sync_after_commit(team_id, identifier)+ return preference, created+++def remove_opt_out(+ team_id: int, identifier: str, category_key: str | None, created_by_id: int | None+) -> tuple[MessageRecipientPreference, bool]:+ category = _category(team_id, category_key) if category_key else None++ preference, created = MessageRecipientPreference.objects.get_or_create(+ team_id=team_id,+ identifier=identifier,+ defaults={"created_by_id": created_by_id},+ )+ preferences = dict(preference.preferences or {})++ if category is None:+ preferences[ALL_MESSAGE_PREFERENCE_CATEGORY_ID] = PreferenceStatus.OPTED_IN.value+ else:+ _lift_global_opt_out(team_id, preferences, category)+ preferences[str(category.id)] = PreferenceStatus.OPTED_IN.value++ preference.preferences = preferences+ preference.save(update_fields=["preferences", "updated_at"])++ _sync_after_commit(team_id, identifier)+ return preference, created+++def _lift_global_opt_out(team_id: int, preferences: dict[str, Any], category: MessageCategory) -> None:+ """Clear a `$all` opt-out that would otherwise swallow a per-category resubscribe.++ Sends check the category and `$all` together, so opting someone back in to one category+ does nothing while `$all` stays opted out. Pin the team's other marketing categories to+ opted out first, so lifting `$all` resubscribes only the category the caller named+ instead of silently widening consent to everything.++ The pinning overwrites even an explicit OPTED_IN on a sibling category (e.g. one a+ Customer.io webhook recorded): while `$all` was opted out that opt-in was inert, so+ preserving the recipient's effective state means opting the sibling out, not letting+ the stale opt-in spring back to life.+ """+ if category.category_type != MessageCategoryType.MARKETING:+ return+ if preferences.get(ALL_MESSAGE_PREFERENCE_CATEGORY_ID) != PreferenceStatus.OPTED_OUT.value:+ return++ other_category_ids = (+ MessageCategory.objects.filter(team_id=team_id, category_type=MessageCategoryType.MARKETING, deleted=False)+ .exclude(id=category.id)+ .values_list("id", flat=True)+ )+ for other_category_id in other_category_ids:+ preferences[str(other_category_id)] = PreferenceStatus.OPTED_OUT.value++ preferences[ALL_MESSAGE_PREFERENCE_CATEGORY_ID] = PreferenceStatus.OPTED_IN.value+++def export_rows(team_id: int, category_key: str | None) -> Iterator[str]:+ return OptOutService(team_id=team_id).export_rows(category_key)+++def bulk_opt_out(+ team_id: int, entries: list[BulkOptOutEntry], default_category_key: str | None, created_by_id: int | None+) -> BulkOptOutResult:+ return OptOutService(team_id=team_id, created_by_id=created_by_id).opt_out_recipients(entries, default_category_key)diff --git a/pyproject.toml b/pyproject.tomlindex e6b3f44b5a93..68adca17d9f3 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -753,10 +753,6 @@ ignore_imports = ["products.messaging.backend.presentation.views.message_suppression -> products.messaging.backend.models.message_suppression",# Lane B: categories, Customer.io config and the Customer.io webhook# Lane C: preferences and the recipient preferences page- "products.messaging.backend.presentation.views.message_preferences -> products.messaging.backend.models.message_category",- "products.messaging.backend.presentation.views.message_preferences -> products.messaging.backend.models.message_preferences",- "products.messaging.backend.presentation.views.message_preferences -> products.messaging.backend.services.opt_out_service",- "products.messaging.backend.presentation.views.message_preferences -> products.messaging.backend.tasks","products.messaging.backend.presentation.views.recipient_preferences -> products.messaging.backend.models.message_category","products.messaging.backend.presentation.views.recipient_preferences -> products.messaging.backend.models.message_preferences","products.messaging.backend.presentation.views.recipient_preferences -> products.messaging.backend.services.customerio_sync_service",