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.

feat(messaging): keep a transactional template's workflow in step on save (#117785)

Harley Alexanderc265837b6cea
diff --git a/products/messaging/backend/facade/transactional_email.py b/products/messaging/backend/facade/transactional_email.py
index 0b29aa6f1093..d25a22f78160 100644
--- a/products/messaging/backend/facade/transactional_email.py
+++ b/products/messaging/backend/facade/transactional_email.py
@@ -1,9 +1,17 @@
"""Transactional email: a template made sendable over the API, backed by a workflow that runs once per send."""
from products.messaging.backend.facade.contracts import TransactionalEmailError
-from products.messaging.backend.services.transactional_email import make_transactional
+from products.messaging.backend.services.transactional_email import (
+ check_transactional_update,
+ lock_transactional_workflow_id,
+ make_transactional,
+ sync_transactional_workflow,
+)
__all__ = [
"TransactionalEmailError",
+ "check_transactional_update",
+ "lock_transactional_workflow_id",
"make_transactional",
+ "sync_transactional_workflow",
]
diff --git a/products/messaging/backend/presentation/views/message_templates.py b/products/messaging/backend/presentation/views/message_templates.py
index 2454ed242e53..1cd4998111a5 100644
--- a/products/messaging/backend/presentation/views/message_templates.py
+++ b/products/messaging/backend/presentation/views/message_templates.py
@@ -3,6 +3,8 @@ from dataclasses import fields as dataclass_fields
from types import SimpleNamespace
from typing import Any
+from django.db import transaction
+
import structlog
import posthoganalytics
from drf_spectacular.types import OpenApiTypes
@@ -46,9 +48,17 @@ from products.messaging.backend.facade.templates import (
team_category_id,
update_template,
)
-from products.messaging.backend.facade.transactional_email import TransactionalEmailError, make_transactional
+from products.messaging.backend.facade.transactional_email import (
+ TransactionalEmailError,
+ check_transactional_update,
+ lock_transactional_workflow_id,
+ make_transactional,
+ sync_transactional_workflow,
+)
from products.messaging.backend.presentation.views.serializers import DesignOperationSerializer
from products.notifications.backend.facade.api import publish_resource_edited
+from products.workflows.backend.facade.api import WorkflowAccessDenied, WorkflowNotFound
+from products.workflows.backend.facade.workflows import get_workflow
logger = structlog.get_logger(__name__)
@@ -188,7 +198,7 @@ class MessageTemplateSerializer(serializers.Serializer):
read_only=True,
allow_null=True,
help_text="The workflow that sends this template over the transactional email API. Null until the "
- "template is made transactional.",
+ "template is made transactional. Each content save writes a new version of it.",
)
def validate(self, data: Any) -> Any:
@@ -361,10 +371,47 @@ class MessageTemplatesViewSet(
template = self.get_object()
serializer = self.get_serializer(self._with_creators([template])[0], data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
- updated = update_template(self.team_id, template.id, serializer.validated_data)
+ # Sends use the workflow's copy, so the template and its new workflow version are saved together,
+ # under a row lock that keeps a concurrent make_transactional from slipping in between.
+ with transaction.atomic():
+ hog_flow_id = lock_transactional_workflow_id(self.team_id, template.id)
+ if hog_flow_id:
+ self._require_workflow_editor(hog_flow_id)
+ try:
+ check_transactional_update(template.id, self.team_id, serializer.validated_data)
+ except TransactionalEmailError as e:
+ raise TransactionalEmailRejected(e) from None
+ updated = update_template(self.team_id, template.id, serializer.validated_data)
+ if hog_flow_id and not updated.deleted:
+ self._sync_transactional_workflow(template.id)
+ # The sync unlinks the template when its workflow was deleted.
+ updated = get_template(self.team_id, template.id)
self._emit_resource_edited(updated)
return Response(self._serialize(updated))
+ def _sync_transactional_workflow(self, template_id: Any) -> None:
+ # Raising rolls back the template save, so the template and its workflow never disagree.
+ try:
+ sync_transactional_workflow(self.team_id, template_id, user_id=self._actor_id())
+ except TransactionalEmailError as e:
+ raise TransactionalEmailRejected(e) from None
+
+ def _require_workflow_editor(self, hog_flow_id: Any) -> None:
+ # The template's own access rules don't cover the workflow it sends through, which can carry its own.
+ try:
+ get_workflow(
+ team_id=self.team_id,
+ workflow_id=str(hog_flow_id),
+ user_access_control=self.user_access_control,
+ required_level="editor",
+ )
+ except WorkflowAccessDenied:
+ raise exceptions.PermissionDenied(
+ "You need editor access to this template's transactional email workflow."
+ ) from None
+ except WorkflowNotFound:
+ return
+
def _actor_id(self) -> int | None:
return self.request.user.id if self.request.user.is_authenticated else None
@@ -427,7 +474,16 @@ class MessageTemplatesViewSet(
serializer.is_valid(raise_exception=True)
return serializer.validated_data["content"]
- locked = edit_template_content(self.team_id, template.id, apply_operations)
+ with transaction.atomic():
+ # Checked under the row lock, so a template made transactional meanwhile is checked too.
+ hog_flow_id = lock_transactional_workflow_id(self.team_id, template.id)
+ if hog_flow_id:
+ self._require_workflow_editor(hog_flow_id)
+ locked = edit_template_content(self.team_id, template.id, apply_operations)
+ if hog_flow_id:
+ self._sync_transactional_workflow(template.id)
+ # The sync unlinks the template when its workflow was deleted.
+ locked = get_template(self.team_id, template.id)
self._emit_resource_edited(locked)
return Response(self._serialize(locked))
diff --git a/products/messaging/backend/services/transactional_email.py b/products/messaging/backend/services/transactional_email.py
index 8d979570d68c..f8889bccca18 100644
--- a/products/messaging/backend/services/transactional_email.py
+++ b/products/messaging/backend/services/transactional_email.py
@@ -1,20 +1,29 @@
"""Transactional emails: a template made sendable over the API. Each one is backed by a workflow that runs once
per send, so sends get the workflow's metrics, run history and versions."""
+from typing import Any
from uuid import UUID
from django.db import transaction
+import structlog
+
+from posthog.plugins.plugin_server_api import reload_hog_flows_on_workers
+
from products.messaging.backend.facade.contracts import MarketingTemplate, SenderUnavailable, TemplateNotSendable
from products.messaging.backend.models import MessageCategory, MessageTemplate
from products.messaging.backend.models.message_category import MessageCategoryType
from products.workflows.backend.facade.api import WorkflowNotFound, get_workflow_summary
from products.workflows.backend.facade.transactional_emails import (
TransactionalEmailContent,
+ TransactionalEmailContentInvalid,
TransactionalEmailSenderUnavailable,
create_transactional_email_workflow,
+ update_transactional_email_workflow,
)
+logger = structlog.get_logger(__name__)
+
def check_sendable(team_id: int, *, template_type: str, content: dict, message_category_id: UUID | None) -> None:
"""Raise when a template with these fields can't be a transactional email."""
@@ -82,3 +91,69 @@ def _workflow_exists(team_id: int, hog_flow_id: UUID) -> bool:
except WorkflowNotFound:
return False
return True
+
+
+def lock_transactional_workflow_id(team_id: int, template_id: UUID) -> UUID | None:
+ """Lock the template row for the rest of the transaction and return its workflow id. Holding the lock
+ keeps make_transactional from linking a workflow between this read and the update that follows."""
+ return (
+ MessageTemplate.objects.select_for_update()
+ .filter(team_id=team_id, id=template_id)
+ .values_list("transactional_hog_flow_id", flat=True)
+ .get()
+ )
+
+
+def check_transactional_update(template_id: UUID, team_id: int, fields: dict[str, Any]) -> None:
+ """Raise when an update would leave a transactional template unable to send. `fields` are validated
+ serializer fields, where `message_category` holds a category id."""
+ template = MessageTemplate.objects.get(team_id=team_id, id=template_id)
+ if not template.transactional_hog_flow_id or fields.get("deleted"):
+ return
+ # A link to a deleted workflow no longer restricts the template. The sync after the update clears it.
+ if not _workflow_exists(team_id, template.transactional_hog_flow_id):
+ return
+ check_sendable(
+ team_id,
+ template_type=fields.get("type", template.type),
+ content=fields.get("content", template.content),
+ message_category_id=fields.get("message_category", template.message_category_id),
+ )
+
+
+def _reload_workers(team_id: int, hog_flow_id: UUID) -> None:
+ # The edit is already committed, so a failed reload must not fail the request. Workers still pick up the
+ # new version when their cache expires.
+ try:
+ reload_hog_flows_on_workers(team_id=team_id, hog_flow_ids=[str(hog_flow_id)])
+ except Exception:
+ logger.exception("transactional_email_worker_reload_failed", team_id=team_id, hog_flow_id=str(hog_flow_id))
+
+
+def sync_transactional_workflow(team_id: int, template_id: UUID, *, user_id: int | None) -> None:
+ """Write the template's current content as a new version of its workflow, if it has one."""
+ template = MessageTemplate.objects.get(team_id=team_id, id=template_id)
+ if not template.transactional_hog_flow_id or template.deleted:
+ return
+ hog_flow_id = template.transactional_hog_flow_id
+ if not _workflow_exists(team_id, hog_flow_id):
+ # Someone deleted the workflow. The template stops being transactional and can be made so again.
+ MessageTemplate.objects.filter(team_id=team_id, id=template_id).update(transactional_hog_flow_id=None)
+ return
+ try:
+ update_transactional_email_workflow(
+ team_id=team_id,
+ user_id=user_id,
+ hog_flow_id=hog_flow_id,
+ content=_content(template, from_integration_id=None),
+ )
+ # The save already told the workers to reload, but before the caller's transaction committed, so a
+ # worker can cache the old version. This reload runs once the new version is visible.
+ transaction.on_commit(lambda: _reload_workers(team_id, hog_flow_id))
+ except WorkflowNotFound:
+ # Deleted between the check above and the update.
+ MessageTemplate.objects.filter(team_id=team_id, id=template_id).update(transactional_hog_flow_id=None)
+ except TransactionalEmailContentInvalid as e:
+ raise TemplateNotSendable("The template needs a subject and a body to send.") from e
+ except TransactionalEmailSenderUnavailable as e:
+ raise SenderUnavailable("No verified email sender. Verify a sending domain first.") from e
diff --git a/products/messaging/backend/tests/api/test_transactional_email.py b/products/messaging/backend/tests/api/test_transactional_email.py
index 4b4f79a92ba7..876a0dbdc125 100644
--- a/products/messaging/backend/tests/api/test_transactional_email.py
+++ b/products/messaging/backend/tests/api/test_transactional_email.py
@@ -1,3 +1,4 @@
+from typing import Any
from uuid import uuid4
import pytest
@@ -50,6 +51,57 @@ class TestTransactionalEmail(APIBaseTest):
assert response.status_code == status.HTTP_200_OK, response.json()
return response.json()
+ @parameterized.expand(
+ [
+ ("update", "", {"name": "Reset"}),
+ (
+ "design",
+ "design/",
+ {"operations": [{"op": "update_content", "id": "txt1", "patch": {"values": {"text": "<p>New</p>"}}}]},
+ ),
+ ]
+ )
+ @patch(
+ "products.messaging.backend.presentation.views.message_templates.render_design_html",
+ return_value="<p>New</p>",
+ )
+ def test_a_deleted_workflow_unlinks_the_template_until_it_is_made_transactional_again(
+ self, _name, suffix, body, _render, mock_post, _flag, _capture
+ ):
+ design = {
+ "body": {
+ "id": "body1",
+ "rows": [
+ {
+ "id": "row1",
+ "cells": [1],
+ "columns": [
+ {
+ "id": "col1",
+ "contents": [{"id": "txt1", "type": "text", "values": {"text": "<p>Old</p>"}}],
+ "values": {},
+ }
+ ],
+ "values": {},
+ }
+ ],
+ "values": {},
+ }
+ }
+ MessageTemplate.objects.filter(id=self.template.id).update(
+ content={"email": {**self.template.content["email"], "design": design}}
+ )
+ deleted = self.client.delete(f"/api/projects/{self.team.id}/hog_flows/{self.hog_flow_id}")
+ assert deleted.status_code == status.HTTP_204_NO_CONTENT
+ template_url = f"/api/projects/{self.team.id}/messaging_templates/{self.template.id}/"
+
+ edited = self.client.patch(f"{template_url}{suffix}", body, format="json")
+ remade = self.client.post(f"{template_url}make_transactional/", {}, format="json")
+
+ assert edited.status_code == status.HTTP_200_OK, edited.json()
+ assert edited.json()["transactional_hog_flow_id"] is None
+ assert remade.json()["transactional_hog_flow_id"] not in (None, str(self.hog_flow_id))
+
def test_is_hidden_while_the_flag_is_off(self, mock_post, flag, _capture):
flag.return_value = False
@@ -117,6 +169,68 @@ class TestTransactionalEmail(APIBaseTest):
template.refresh_from_db()
assert template.transactional_hog_flow_id is None
+ @patch("products.messaging.backend.services.transactional_email.reload_hog_flows_on_workers")
+ def test_saving_a_transactional_template_writes_a_new_workflow_version(self, reload, mock_post, _flag, _capture):
+ with self.captureOnCommitCallbacks(execute=True):
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/messaging_templates/{self.template.id}/",
+ {"content": {"email": {"subject": "A new subject", "html": "<p>New</p>"}}},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ # Workers reload once the new version is committed, not only from inside the transaction.
+ reload.assert_called_once_with(team_id=self.team.id, hog_flow_ids=[str(self.hog_flow_id)])
+ workflow = self._workflow(self.hog_flow_id)
+ assert workflow["version"] == 2
+ email = workflow["actions"][1]["config"]["inputs"]["email"]["value"]
+ assert (email["subject"], email["html"]) == ("A new subject", "<p>New</p>")
+
+ @parameterized.expand([("marketing_category",), ("no_email_content",)])
+ def test_a_template_whose_workflow_was_deleted_takes_edits_it_could_not_send_with(
+ self, mock_post, _flag, _capture, edit
+ ):
+ category = MessageCategory.objects.create(
+ team=self.team, key="news", name="News", category_type=MessageCategoryType.MARKETING
+ )
+ body: dict[str, Any] = (
+ {"message_category": str(category.id)} if edit == "marketing_category" else {"content": {}}
+ )
+ self.client.delete(f"/api/projects/{self.team.id}/hog_flows/{self.hog_flow_id}")
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/messaging_templates/{self.template.id}/", body, format="json"
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["transactional_hog_flow_id"] is None
+
+ def test_deleting_a_transactional_template_succeeds(self, mock_post, _flag, _capture):
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/messaging_templates/{self.template.id}/", {"deleted": True}, format="json"
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ self.template.refresh_from_db()
+ assert self.template.deleted
+
+ def test_rejects_an_update_that_would_stop_a_transactional_template_sending(self, mock_post, _flag, _capture):
+ category = MessageCategory.objects.create(
+ team=self.team, key="news", name="News", category_type=MessageCategoryType.MARKETING
+ )
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/messaging_templates/{self.template.id}/",
+ {"message_category": str(category.id)},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["code"] == "marketing_template"
+ self.template.refresh_from_db()
+ assert self.template.message_category_id is None
+ assert self._workflow(self.hog_flow_id)["version"] == 1
+
@pytest.mark.ee
@patch(
@@ -159,6 +273,19 @@ class TestTransactionalEmailWorkflowAccess(APIBaseTest):
)
self.client.force_login(member)
+ @parameterized.expand(
+ [
+ ("update", "patch", "", {"content": {"email": {"subject": "New", "html": "<p>New</p>"}}}),
+ ]
+ )
+ def test_a_member_denied_the_workflow_cannot_change_it(self, mock_post, _flag, _name, method, suffix, body):
+ url = f"/api/projects/{self.team.id}/messaging_templates/{self.template.id}/{suffix}"
+
+ response = getattr(self.client, method)(url, body, format="json")
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+ mock_post.assert_not_called()
+
@parameterized.expand([("unlinked", None), ("linked_to_a_deleted_workflow", uuid4())])
def test_editor_access_to_one_workflow_cannot_create_another(self, mock_post, _flag, _name, linked_hog_flow_id):
self._login_member("[email protected]", {None: "viewer", str(self.hog_flow_id): "editor"})
diff --git a/products/messaging/frontend/generated/api.schemas.ts b/products/messaging/frontend/generated/api.schemas.ts
index 73b876311bbd..0576f0265791 100644
--- a/products/messaging/frontend/generated/api.schemas.ts
+++ b/products/messaging/frontend/generated/api.schemas.ts
@@ -396,7 +396,7 @@ export interface MessageTemplateApi {
/** Soft-delete flag. Set true to remove the template from the library. */
deleted?: boolean
/**
- * The workflow that sends this template over the transactional email API. Null until the template is made transactional.
+ * The workflow that sends this template over the transactional email API. Null until the template is made transactional. Each content save writes a new version of it.
* @nullable
*/
readonly transactional_hog_flow_id: string | null
@@ -438,7 +438,7 @@ export interface PatchedMessageTemplateApi {
/** Soft-delete flag. Set true to remove the template from the library. */
deleted?: boolean
/**
- * The workflow that sends this template over the transactional email API. Null until the template is made transactional.
+ * The workflow that sends this template over the transactional email API. Null until the template is made transactional. Each content save writes a new version of it.
* @nullable
*/
readonly transactional_hog_flow_id?: string | null
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 90abbf732c21..cf7330f363fb 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -66900,7 +66900,7 @@ export namespace Schemas {
/** Soft-delete flag. Set true to remove the template from the library. */
deleted?: boolean;
/**
- * The workflow that sends this template over the transactional email API. Null until the template is made transactional.
+ * The workflow that sends this template over the transactional email API. Null until the template is made transactional. Each content save writes a new version of it.
* @nullable
*/
readonly transactional_hog_flow_id: string | null;
@@ -82845,7 +82845,7 @@ export namespace Schemas {
/** Soft-delete flag. Set true to remove the template from the library. */
deleted?: boolean;
/**
- * The workflow that sends this template over the transactional email API. Null until the template is made transactional.
+ * The workflow that sends this template over the transactional email API. Null until the template is made transactional. Each content save writes a new version of it.
* @nullable
*/
readonly transactional_hog_flow_id?: string | null;