diff --git a/.github/scripts/check_strict_types.sh b/.github/scripts/check_strict_types.sh index 149b10d86..65c0e0b40 100755 --- a/.github/scripts/check_strict_types.sh +++ b/.github/scripts/check_strict_types.sh @@ -16,7 +16,7 @@ from datetime import datetime, timezone import posthog from posthog import FeatureFlagEvaluations, FlagValue, Posthog -from posthog.emails import AsyncEmails, Emails, SendEmailResult +from posthog.emails import AsyncEmails, BatchEmailResult, EmailBatchError, EmailError, Emails, SendBatchResult, SendEmailResult from posthog.ai.evaluations import ( AsyncOfflineEvaluations, BooleanScorerConfig, @@ -54,12 +54,23 @@ not_sensitive_send: SendEmailResult = emails.send(to="user@example.com", templat scheduled_send: SendEmailResult = emails.send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", scheduled_at=datetime(2026, 12, 1, tzinfo=timezone.utc)) scheduled_status: str = scheduled_send.status scheduled_time: datetime | None = scheduled_send.scheduled_at -_ = (template_send, rendered_send, invite_send, tracked_send, untracked_send, not_sensitive_send, scheduled_status, scheduled_time) +template_batch: SendBatchResult = emails.batch(template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", template_data={"team": "Data"}, recipients=[{"to": "ada@example.com", "distinct_id": "user_1", "idempotency_key": "invite:user_1", "template_data": {"name": "Ada"}}]) +code_batch: SendBatchResult = emails.batch(template_key="digest", subject="Digest", html="
Digest
", recipients=[{"to": "ada@example.com"}], max_retries=0) +first_batch_result: BatchEmailResult = template_batch.results[0] +batch_status: str = first_batch_result.status +batch_error_field: EmailError | None = first_batch_result.error +try: + emails.batch(template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", recipients=[{"to": "ada@example.com"}]) +except EmailBatchError as batch_error: + failed_results: tuple[BatchEmailResult, ...] = batch_error.results + _ = failed_results +_ = (template_send, rendered_send, invite_send, tracked_send, untracked_send, not_sensitive_send, scheduled_status, scheduled_time, code_batch, batch_status, batch_error_field) async def async_email_types() -> None: sent: SendEmailResult = await AsyncEmails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="Hi
", scheduled_at="2026-12-01T09:00:00Z") - _ = sent + batch: SendBatchResult = await AsyncEmails("phs_example").batch(template_key="welcome", subject="Hi", html="Hi
", recipients=[{"to": "user@example.com"}]) + _ = (sent, batch) async def offline_evaluation_types( @@ -119,6 +130,10 @@ Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3 Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="Hi
", tracking={"open": False}) # expected-type-error Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="Hi
", template_data={"name": "Ada"}) # expected-type-error Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="Hi
", scheduled_at=1796115600) # expected-type-error +Emails("phs_example").batch(template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", recipients=[{"to": "user@example.com"}], scheduled_at="2026-12-01T09:00:00Z") # expected-type-error +Emails("phs_example").batch(template_key="welcome", subject="Hi", html="Hi
", recipients=[{"to": "user@example.com"}], cc="team@example.com") # expected-type-error +Emails("phs_example").batch(template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", recipients=[{"email": "user@example.com"}]) # expected-type-error +Emails("phs_example").batch(template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", to="user@example.com", recipients=[{"to": "user@example.com"}]) # expected-type-error Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="Hi
", attachments=[{"filename": "a.txt", "content": [104, 105]}]) # expected-type-error Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="Hi
", attachments=[{"filename": "a.txt", "content": b"hi", "path": "/tmp/a.txt"}]) # expected-type-error Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", attachments=[{"filename": "a.txt", "content": b"hi"}]) # expected-type-error diff --git a/.sampo/changesets/email-batch-sends.md b/.sampo/changesets/email-batch-sends.md new file mode 100644 index 000000000..d0a5dd066 --- /dev/null +++ b/.sampo/changesets/email-batch-sends.md @@ -0,0 +1,5 @@ +--- +pypi/posthog: minor +--- + +Send the same transactional email to up to 100 recipients in one request with `emails.batch()`, one email each, from a template with `template_data` per recipient or from content in your code. More than 100 recipients raises `ValueError` before anything is sent. The client gives each recipient an idempotency key that every retry reuses, and returns a result per recipient: `queued`, `failed` or `unconfirmed`. A request that fails as a whole, such as a `413` `content_too_large`, raises `EmailBatchError` with every recipient's result. diff --git a/posthog/emails.py b/posthog/emails.py index f7c5134e9..5d3a7bf70 100644 --- a/posthog/emails.py +++ b/posthog/emails.py @@ -143,6 +143,50 @@ print(result.status, result.scheduled_at) # scheduled, the time in UTC ``` +Batches: ``emails.batch`` sends the same template or content to up to 100 +recipients in one request, one email each, with ``template_data`` per recipient +for a template. It waits 45 seconds for the answer. Each recipient has its own +``idempotency_key``, given or made by the client, that every retry reuses. +Check each result's ``status``: + +- ``queued``: PostHog accepted the email. +- ``failed``: PostHog refused it, and ``error`` says why, such as a suppressed + address. +- ``unconfirmed``: the client can't tell whether PostHog accepted it, such as + after a lost answer or a 409 other than ``batch_unavailable``. Send it again + with the same key within 24 hours of the first request that used it, so it + goes out once. After a lost answer, a later refusal of the whole request + leaves every recipient ``unconfirmed`` too, and its error says some emails + may still go out. + +More than 100 recipients raises ``ValueError`` before anything is sent. A request +that fails as a whole, such as a rate limit past its retries, raises +:class:`EmailBatchError`, whose ``results`` hold every recipient. ``code`` +``content_too_large`` on a 413 means the request was larger than PostHog takes +at once: split the recipients into smaller batches, as its ``fix`` says, and +when the shared content or ``template_data`` alone passes the limit, which +splitting doesn't help, send less of it. On a 400 it means the shared content or +``template_data`` is too large to copy to every recipient, and its ``message`` +says what to send less of. ``batch_unavailable`` (409) means the project +can't send batches yet: send each email the batch didn't queue with ``send`` +and its recipient's ``idempotency_key``. A 404 ``not_found`` that names no +``field`` means PostHog found no template with that ``template_id``, or batch +sends aren't available for the project: check the template ID, and if it's +right, send each recipient on its own with ``send``, the same content and its +recipient's ``idempotency_key``, until batch sends are available. A batch takes no ``cc``, ``bcc``, +``attachments`` or ``scheduled_at``. + +```python +result = posthog.emails.batch( + template_id="", + recipients=[ + {"to": "ada@example.com", "template_data": {"name": "Ada"}}, + {"to": "alan@example.com", "template_data": {"name": "Alan"}}, + ], +) +retry = [r for r in result.results if r.status == "unconfirmed"] +``` + Cleanup: ``shutdown()`` on the client closes its email connections. Close a standalone :class:`Emails` with ``close()`` or a ``with`` block. @@ -199,14 +243,20 @@ __all__ = [ "AsyncEmails", + "BatchEmailResult", + "BatchRecipient", + "CodeBatchArgs", "CodeEmailArgs", "EmailAttachment", + "EmailBatchError", "EmailError", "EmailStatus", "EmailTracking", "EmailWarning", "Emails", + "SendBatchResult", "SendEmailResult", + "TemplateBatchArgs", "TemplateEmailArgs", ] @@ -215,11 +265,16 @@ _SEND_PATH = "/api/messaging/send/email/" _UPLOADS_PATH = "/api/messaging/attachments/uploads/" _STATUS_PATH = "/api/messaging/emails/{message_id}/" +_BATCH_PATH = "/api/messaging/send/email_batch/" +_BATCH_MAX_RECIPIENTS = 100 +_POSTHOG_PIPELINE_WAIT = 30.0 +_BATCH_ATTEMPT_TIMEOUT = _POSTHOG_PIPELINE_WAIT + 15.0 _TEMPLATE_KEY = re.compile(r"[a-zA-Z0-9_-]{1,400}") _MAX_RETRY_DELAY = 30.0 _IDEMPOTENCY_KEY = re.compile(r"^[\x21-\x7e]{1,255}$") _HEADER_TOKEN = re.compile(r"[\x21-\x7e]+") _IN_FLIGHT_CODES = frozenset({"idempotency_key_in_flight"}) +_UNCONFIRMED_SLOT_CODES = _IN_FLIGHT_CODES | {"delivery_unavailable", "api_error"} _QUOTA_CODES = frozenset({"quota_limited"}) _DAILY_QUOTA_CODES = frozenset({"upload_quota_exceeded"}) _MAX_ATTACHMENTS = 10 @@ -519,6 +574,166 @@ class EmailStatus: reason: Optional[str] = None +class BatchRecipient(TypedDict): + """One recipient of :meth:`Emails.batch`. Each gets its own email. + + Args: + to: The recipient's email address. + distinct_id: The recipient's distinct ID in your product. + idempotency_key: 1 to 255 visible ASCII characters, a different one + for each recipient of the call. Without it, the client makes one + that covers its own retries but not a second call, so pass keys + you store when a batch may be cut off and run again: a rerun + within 24 hours replays the emails that went out instead of + sending them twice. A single send and a batch recipient with the + same key and the same email replay each other. Never + reuse a key for another email: PostHog refuses a key it saw + with a different recipient, template or data with + ``idempotency_key_reused``, but two such sends at the same moment + can both read ``queued`` while only one email goes out. + template_data: Only with ``template_id``: values for this recipient, + merged over the batch's ``template_data``. A top-level key set here + replaces the same key there. + """ + + to: str + distinct_id: NotRequired[Optional[str]] + idempotency_key: NotRequired[Optional[str]] + template_data: NotRequired[Optional[Mapping[str, Any]]] + + +class _BatchArgs(TypedDict): + recipients: Sequence[BatchRecipient] + max_retries: NotRequired[Optional[int]] + + +class TemplateBatchArgs(_BatchArgs): + """A batch of an email template made in PostHog, named by its ID. + + Args: + recipients: 1 to 100 recipients, sent in one request. + template_id: The UUID of a template made transactional in PostHog. + template_data: Values for the template's ``{{ variables.* }}`` + placeholders, shared by every recipient. + max_retries: Overrides the client's maximum number of retries for + the batch request. ``0`` turns retries off. + """ + + template_id: Union[str, UUID] + template_data: NotRequired[Optional[Mapping[str, Any]]] + + +class CodeBatchArgs(_BatchArgs): + """A batch of email content your code rendered, the same for every recipient. + + Takes the fields of :class:`CodeEmailArgs` but ``to``, ``distinct_id``, + ``idempotency_key``, ``cc``, ``bcc``, ``attachments`` and + ``scheduled_at``. A recipient can't carry ``template_data``: send + personalized content with a ``template_id`` batch, or with + :meth:`Emails.send`. + """ + + template_key: str + subject: str + html: NotRequired[Optional[str]] + text: NotRequired[Optional[str]] + from_: NotRequired[Optional[str]] + reply_to: NotRequired[Optional[Union[str, Sequence[str]]]] + capture_engagement: NotRequired[Optional[bool]] + sensitive: NotRequired[Optional[bool]] + tracking: NotRequired[Optional[Union[bool, EmailTracking]]] + + +_BATCH_RECIPIENT_FIELDS = frozenset(BatchRecipient.__annotations__) + + +BatchStatus = Literal["queued", "failed", "unconfirmed"] + + +@dataclass(frozen=True) +class BatchEmailResult: + """What happened to one recipient of :meth:`Emails.batch`. + + ``status`` is one of: + + - ``queued``: PostHog accepted the email. Read its status with + :meth:`Emails.get` to see whether it went out. + - ``failed``: PostHog didn't queue the email, and ``error`` says why. + - ``unconfirmed``: the client can't tell whether PostHog queued the + email, such as after a lost answer, or a refusal that came after an + attempt got no answer. It may still go out. Send it again with the same + ``idempotency_key`` within 24 hours of the first request that used it, + so it goes out once. + + Attributes: + index: The recipient's position in ``recipients``. + to: The recipient's email address. + idempotency_key: The recipient's key, given or made by the client. + status: One of the values above. + message_id: The email's message ID, when PostHog named it. + replayed: ``True`` when an earlier send with the same key had already + queued the email, so no new email was sent. + error: Why the email is not ``queued``. For an ``unconfirmed`` + email, ``message`` says PostHog didn't confirm it and it may + still go out, ``code`` and ``status_code`` are the last answer's, + and ``fix`` says to send it again with the same key. + """ + + index: int + to: str + idempotency_key: str + status: BatchStatus + message_id: Optional[str] = None + replayed: bool = False + error: Optional[EmailError] = None + + +@dataclass(frozen=True) +class SendBatchResult: + """The answer to :meth:`Emails.batch`. + + Attributes: + results: One result per recipient, in the order of ``recipients``. + warnings: Warnings PostHog returned about the batch, each once. + """ + + results: tuple[BatchEmailResult, ...] + warnings: tuple[EmailWarning, ...] = () + + +class EmailBatchError(EmailError): + """The request of :meth:`Emails.batch` failed as a whole. + + The fields describe that request's error. ``results`` holds every + recipient, as ``failed``, or as ``unconfirmed`` when an attempt got no + answer and may have queued them, or PostHog answered 409 with a code other + than ``batch_unavailable``. Then ``message`` says some emails may still + go out, whatever PostHog answered last, and ``fix`` says to send each + recipient again with the same key and read each recipient's result. + + Attributes: + results: One result per recipient, in the order of ``recipients``. + """ + + def __init__( + self, + error: EmailError, + results: tuple[BatchEmailResult, ...], + ) -> None: + super().__init__( + name=error.name, + code=error.code, + message=error.message, + status_code=error.status_code, + why=error.why, + fix=error.fix, + docs_url=error.docs_url, + field=error.field, + retry_after=error.retry_after, + ) + self.results = results + + @dataclass(frozen=True) class _File: sha256: str @@ -615,13 +830,13 @@ def _prepare_code_send( ) -def _code_content(args: Mapping[str, Any]) -> dict[str, str]: +def _code_content(args: Mapping[str, Any], method: str = "send") -> dict[str, str]: content = {"subject": _nonempty_text(args, "subject")} content.update( {field: _string(args, field) for field in ("html", "text") if field in args} ) if "html" not in content and "text" not in content: - raise TypeError("send() needs html, text or both.") + raise TypeError(f"{method}() needs html, text or both.") if not (content.get("html") or content.get("text")): raise ValueError("html or text must be a nonempty string.") @@ -881,19 +1096,11 @@ def _prepare_send( ) -> _PreparedSend: to, distinct_id, idempotency_key = _recipient(to, distinct_id, idempotency_key) max_retries = _retry_limit(max_retries) - try: - template_uuid = ( - template_id if isinstance(template_id, UUID) else UUID(template_id) - ) - except (TypeError, ValueError, AttributeError): - raise ValueError("template_id must be the template's UUID.") from None - if template_data is not None and not isinstance(template_data, Mapping): - raise TypeError("template_data must be a mapping.") - + template, message_data = _template(template_id, template_data) payload: dict[str, Any] = { - "template_id": str(template_uuid), + "template_id": template, "to": to, - "message_data": clean(dict(template_data or {})), + "message_data": message_data, } if distinct_id is not None: payload["distinct_id"] = distinct_id @@ -907,6 +1114,18 @@ def _prepare_send( ) +def _template(template_id: Any, template_data: Any) -> tuple[str, dict[str, Any]]: + try: + template_uuid = ( + template_id if isinstance(template_id, UUID) else UUID(template_id) + ) + except (TypeError, ValueError, AttributeError): + raise ValueError("template_id must be the template's UUID.") from None + if template_data is not None and not isinstance(template_data, Mapping): + raise TypeError("template_data must be a mapping.") + return str(template_uuid), clean(dict(template_data or {})) + + def _recipient( to: Any, distinct_id: Any, idempotency_key: Any ) -> tuple[str, Optional[str], str]: @@ -1073,7 +1292,7 @@ def _idempotency_error_name(status: int, code: str) -> str: if status == 409: return ( "validation_error" - if code == "template_outdated" + if code in ("template_outdated", "batch_unavailable") else "concurrent_idempotent_requests" ) # The template send route also answers 422 for send checks such as recipient_suppressed. @@ -1401,6 +1620,10 @@ def _response_error( ) +def _held_by_another_request(error: EmailError) -> bool: + return error.status_code == 409 and error.code in _IN_FLIGHT_CODES + + def _is_retryable(error: EmailError) -> bool: # A send carries an idempotency key, so a retry can't queue a second email. A status read changes nothing. if error.status_code is None: @@ -1408,7 +1631,7 @@ def _is_retryable(error: EmailError) -> bool: if error.code == "attachment_upload_failed": return error.status_code in _STORAGE_RETRY_STATUSES if error.status_code == 409: - return error.code in _IN_FLIGHT_CODES + return _held_by_another_request(error) if error.status_code == 429: return error.code not in _QUOTA_CODES | _DAILY_QUOTA_CODES return error.status_code == 503 @@ -1428,7 +1651,7 @@ def _no_op() -> None: pass -def _log_warnings(result: SendEmailResult) -> None: +def _log_warnings(result: Union[SendEmailResult, SendBatchResult]) -> None: for warning in result.warnings: log.warning("PostHog email warning %s: %s", warning.code, warning.message) @@ -1493,6 +1716,355 @@ def _files_body(files: Sequence[_File]) -> bytes: ) +@dataclass(frozen=True) +class _BatchMember: + index: int + to: str + idempotency_key: str + wire: dict[str, Any] + + +def _prepare_batch(args: Mapping[str, Any]) -> _BatchRun: + is_template_form = "template_id" in args + if is_template_form == ("template_key" in args): + raise TypeError("Pass either template_id or template_key.") + form = TemplateBatchArgs if is_template_form else CodeBatchArgs + unexpected = sorted(set(args) - set(form.__annotations__)) + if unexpected: + raise TypeError( + f"batch() got arguments that the {'template' if is_template_form else 'code'} " + f"form doesn't take: {', '.join(unexpected)}. A batch takes no scheduled_at, " + "cc, bcc or attachments, and each recipient's to goes in recipients." + ) + if "recipients" not in args: + raise TypeError("batch() is missing the argument recipients.") + max_retries = _retry_limit(args.get("max_retries")) + shared = ( + _template_batch_email(args) if is_template_form else _code_batch_email(args) + ) + members = _batch_members(args["recipients"], is_template_form) + return _BatchRun(shared, members, max_retries) + + +def _template_batch_email(args: Mapping[str, Any]) -> dict[str, Any]: + template, message_data = _template(args["template_id"], args.get("template_data")) + return {"template_id": template, "message_data": message_data} + + +def _code_batch_email(args: Mapping[str, Any]) -> dict[str, Any]: + args = { + name: value + for name, value in args.items() + if value is not None or name not in _OPTIONAL_CODE_FIELDS + } + if "subject" not in args: + raise TypeError("batch() is missing the argument subject.") + template_key = args["template_key"] + if not isinstance(template_key, str) or not _TEMPLATE_KEY.fullmatch(template_key): + raise ValueError( + "template_key can only have letters, digits, hyphens (-) and underscores (_), at most 400." + ) + return { + "template_key": template_key, + **_code_content(args, "batch"), + **_sender(args), + } + + +def _batch_members(recipients: Any, is_template_form: bool) -> list[_BatchMember]: + if isinstance(recipients, (str, bytes, Mapping)) or not isinstance( + recipients, Sequence + ): + raise TypeError("recipients must be a list of recipients, each a dict with to.") + if not recipients: + raise ValueError("recipients must hold at least one recipient.") + if len(recipients) > _BATCH_MAX_RECIPIENTS: + raise ValueError( + f"A batch takes at most {_BATCH_MAX_RECIPIENTS} recipients, and recipients " + f"holds {len(recipients)}, so no email was sent. Split them into batches " + f"of at most {_BATCH_MAX_RECIPIENTS}." + ) + first_with_key: dict[str, int] = {} + members = [] + for index, recipient in enumerate(recipients): + where = f"recipients[{index}]" + if not isinstance(recipient, Mapping) or "to" not in recipient: + raise TypeError( + f"{where} must be a dict with to, such as {{'to': 'user@example.com'}}." + ) + unknown = sorted(set(recipient) - _BATCH_RECIPIENT_FIELDS) + if unknown: + raise TypeError( + f"{where} takes only to, distinct_id, idempotency_key and template_data, " + f"not {', '.join(unknown)}." + ) + try: + to, distinct_id, key = _recipient( + recipient["to"], + recipient.get("distinct_id"), + recipient.get("idempotency_key"), + ) + except (TypeError, ValueError) as exc: + raise type(exc)(f"{where}: {exc}") from None + wire: dict[str, Any] = {"to": to, "idempotency_key": key} + if distinct_id is not None: + wire["distinct_id"] = distinct_id + data = recipient.get("template_data") + if data is not None: + if not is_template_form: + raise TypeError( + f"{where} has template_data, but a batch with template_key sends the same " + "content to every recipient. Send personalized content with a template_id " + "batch or with send()." + ) + if not isinstance(data, Mapping): + raise TypeError(f"{where}: template_data must be a mapping.") + wire["message_data"] = clean(dict(data)) + first = first_with_key.setdefault(key, index) + if first != index: + raise ValueError( + f"recipients[{index}] has the same idempotency_key as recipients[{first}]. " + "Give each recipient its own key." + ) + members.append(_BatchMember(index, to, key, wire)) + return members + + +_BATCH_NOT_FOUND = { + True: ( + "PostHog found no template with this template_id, or batch sends aren't " + "available for this project", + "Check template_id. If it's right, send each recipient on its own with " + "send() and its idempotency_key until batch sends are available.", + ), + False: ( + "Batch sends or sending from code aren't available for this project", + "If the project can send email from code, send each recipient on its own " + "with send() and its idempotency_key until batch sends are available.", + ), +} + + +def _batch_not_found(template_form: bool) -> dict[str, str]: + cause, fix = _BATCH_NOT_FOUND[template_form] + return { + "code": "not_found", + "detail": cause + ", so PostHog sent no email of this request.", + "fix": fix, + } + + +def _said(value: Any) -> Optional[str]: + text = _text(value) + return text if text and text.strip() else None + + +def _readable_code(fields: Mapping[str, Any]) -> Optional[str]: + return _said(fields.get("code")) + + +def _batch_response_error( + fields: Mapping[str, Any], + status: int, + retry_after_header: Optional[str], + recipient_count: int, + template_form: bool, +) -> EmailError: + fields = {key: value for key, value in fields.items() if value is not None} + code = _readable_code(fields) + if ( + status == 404 + and code in (None, "not_found", "api_error") + and not _text(fields.get("attr")) + ): + fields = _batch_not_found(template_form) + if status == 413 and not _said(fields.get("fix")): + fields = { + **fields, + "fix": "Split the recipients into smaller batches and send each with batch()." + if recipient_count > 1 + else "Send less template_data or content for this recipient.", + } + if fields.get("code") == "batch_unavailable": + fields = { + **fields, + "fix": "Until batch sends are on for the project, send each email the " + "batch didn't queue with send() and its recipient's idempotency_key.", + } + return _response_error(fields, status, retry_after_header) + + +def _slot_error(error: Any, message_id: Optional[str]) -> EmailError: + if not isinstance(error, dict): + return EmailError( + name="application_error", + code="api_error", + message="PostHog answered without a readable result for this email, so it may still go out.", + message_id=message_id, + ) + code = _text(error.get("code")) or "api_error" + status = error.get("status") + status_code = ( + status if isinstance(status, int) and not isinstance(status, bool) else None + ) + return EmailError( + name=_error_name(status_code, code), + code=code, + message=_text(error.get("detail")) + or f"PostHog didn't queue this email: {code}.", + status_code=status_code, + message_id=message_id, + ) + + +_SEND_AGAIN = ( + "Send it again with the same idempotency_key within 24 hours of the first request " + "that used it, so it goes out once." +) + + +_SEND_EACH_AGAIN = ( + "Send each recipient again with the same idempotency_key within 24 hours of the " + "first request that used it, so each email goes out once, and read each " + "recipient's result." +) + + +def _unconfirmed(message_id: Optional[str], cause: EmailError) -> EmailError: + return EmailError( + name=cause.name, + code=cause.code, + message="PostHog didn't confirm this email, so it may still go out.", + status_code=cause.status_code, + fix=_SEND_AGAIN, + docs_url=cause.docs_url, + field=cause.field, + retry_after=cause.retry_after, + message_id=message_id, + ) + + +class _BatchRun: + """The one request of a batch call, and what PostHog answered for each recipient.""" + + def __init__( + self, + shared: Mapping[str, Any], + members: list[_BatchMember], + max_retries: Optional[int], + ) -> None: + self.members = members + self.max_retries = max_retries + self.body = _encode( + {**shared, "recipients": [member.wire for member in members]} + ) + self.results: tuple[BatchEmailResult, ...] = () + self.warnings: list[EmailWarning] = [] + self.maybe_queued = False + self.template_form = "template_id" in shared + + def _result( + self, member: _BatchMember, status: BatchStatus, **fields: Any + ) -> BatchEmailResult: + return BatchEmailResult( + index=member.index, + to=member.to, + idempotency_key=member.idempotency_key, + status=status, + **fields, + ) + + def lost(self) -> None: + """An attempt got no usable answer, so it may have queued every recipient.""" + self.maybe_queued = True + + def answer( + self, + status: int, + body: bytes, + retry_after_header: Optional[str], + ) -> None: + fields = _json_object(body) + if not 200 <= status < 300: + failure = _batch_response_error( + fields, + status, + retry_after_header, + len(self.members), + self.template_form, + ) + unsettled_conflict = ( + status == 409 and _readable_code(fields) != "batch_unavailable" + ) + if status >= 500 or unsettled_conflict: + self.lost() + raise failure + slots = fields.get("results") + if not isinstance(slots, list) or len(slots) != len(self.members): + self.lost() + raise _sdk_error( + "api_error", + "PostHog answered the batch without a result for each recipient.", + status, + ) + self.results = tuple( + self._settle(member, slot if isinstance(slot, dict) else {}) + for member, slot in zip(self.members, slots) + ) + for warning in _parse_warnings(fields.get("warnings")): + if warning not in self.warnings: + self.warnings.append(warning) + + def _settle( + self, member: _BatchMember, slot: Mapping[str, Any] + ) -> BatchEmailResult: + message_id = _text(slot.get("message_id")) + error = slot.get("error") + if error is None and slot.get("status") == "queued" and message_id: + return self._result( + member, + "queued", + message_id=message_id, + replayed=slot.get("replayed") is True, + ) + answer = _slot_error(error, message_id) + if self.maybe_queued or answer.code in _UNCONFIRMED_SLOT_CODES: + return self._result( + member, + "unconfirmed", + message_id=message_id, + error=_unconfirmed(message_id, answer), + ) + return self._result(member, "failed", message_id=message_id, error=answer) + + def result(self) -> SendBatchResult: + return SendBatchResult(results=self.results, warnings=tuple(self.warnings)) + + def failure(self, error: EmailError) -> EmailBatchError: + """The request failed as a whole, so every recipient shares its error.""" + if self.maybe_queued: + results = tuple( + self._result(member, "unconfirmed", error=_unconfirmed(None, error)) + for member in self.members + ) + error = EmailError( + name=error.name, + code=error.code, + message="PostHog didn't confirm this batch, so some of its emails " + "may still go out.", + status_code=error.status_code, + fix=_SEND_EACH_AGAIN, + docs_url=error.docs_url, + field=error.field, + retry_after=error.retry_after, + ) + else: + results = tuple( + self._result(member, "failed", error=error) for member in self.members + ) + return EmailBatchError(error, results) + + class _EmailsBase: def __init__( self, @@ -1530,6 +2102,29 @@ def _start(self, not_done: str) -> Callable[[], None]: ) return finish + def _still_admitted(self) -> bool: + finish = self._admit() + if finish is None: + return False + finish() + return True + + def _retry_while_admitted(self) -> Callable[[], None]: + """Before each retry of a batch request, stop when the client shut down.""" + attempts = 0 + + def check() -> None: + nonlocal attempts + attempts += 1 + if attempts > 1 and not self._still_admitted(): + raise _sdk_error( + "client_closed", + "The PostHog client is shut down, so it didn't retry the " + "batch request.", + ) + + return check + def _secret_key(self, key_needed: str) -> str: if self._host_error: raise _sdk_error("missing_app_host", self._host_error) @@ -1537,6 +2132,9 @@ def _secret_key(self, key_needed: str) -> str: raise _sdk_error("missing_secret_key", key_needed) return self.secret_key + def _batch_timeout(self) -> float: + return max(float(self.timeout), _BATCH_ATTEMPT_TIMEOUT) + def _check_schedulable(self, prepared: _PreparedSend) -> None: if prepared.scheduled_at is None or self.host in ( US_APP_ENDPOINT, @@ -1685,6 +2283,105 @@ def send(self, **kwargs: Any) -> SendEmailResult: _log_warnings(result) return result + @overload + def batch(self, **kwargs: Unpack[TemplateBatchArgs]) -> SendBatchResult: ... + + @overload + def batch(self, **kwargs: Unpack[CodeBatchArgs]) -> SendBatchResult: ... + + def batch(self, **kwargs: Any) -> SendBatchResult: + """Queue the same email for up to 100 recipients, one email each. + + Pass the template form, with ``template_id``, or the code form, with + ``template_key``: see :class:`TemplateBatchArgs` and + :class:`CodeBatchArgs`. The client sends every recipient in one + request. + + Each recipient has an ``idempotency_key``, given or made by the + client, that every retry reuses, so a retry never queues an email + twice. + + Args: + recipients: 1 to 100 recipients, each a :class:`BatchRecipient`. + template_id: The UUID of a template made transactional in PostHog. + template_data: Values for the template, shared by every recipient. + template_key: Names the email of the code form. With it, pass the + content as :meth:`send` takes it. + max_retries: Overrides the client's maximum number of retries for + the request. ``0`` turns retries off. + + Returns: + A result per recipient, in the order of ``recipients``. Check each + ``status``: ``queued``, ``failed`` or ``unconfirmed``. Send an + ``unconfirmed`` email again with the same key to make sure it goes + out once. + + Raises: + EmailBatchError: The request failed as a whole. ``results`` holds + every recipient. ``code`` is ``content_too_large`` on a 413 when + the request was larger than PostHog takes at once: split the + recipients into smaller batches, or send less shared content + or ``template_data`` when that alone passes the limit. On a 400 + the shared content or ``template_data`` is too large to copy to + every recipient, and ``message`` says what to send less of. ``batch_unavailable`` means the project + can't send batches yet: send each email the batch didn't + queue with :meth:`send` and its recipient's + ``idempotency_key``. ``client_closed`` means the client shut + down before a retry. + EmailError: The client sent nothing, such as when it is disabled. + TypeError, ValueError: An argument has the wrong type or format, + such as more than 100 recipients or two recipients with the + same ``idempotency_key``. + + Examples: + ```python + result = emails.batch( + template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", + recipients=[ + {"to": "ada@example.com", "template_data": {"name": "Ada"}}, + {"to": "alan@example.com", "template_data": {"name": "Alan"}}, + ], + ) + for email in result.results: + if email.status != "queued": + print(email.to, email.status, email.error) + ``` + """ + run = _prepare_batch(kwargs) + finish = self._start(_SEND_NOT_DONE) + try: + secret_key = self._secret_key(_SEND_KEY_NEEDED) + headers = _headers(secret_key, self.migrated_from, has_body=True) + try: + self._call( + self._batch_attempt(run, headers), run.answer, run.max_retries + ) + except EmailError as error: + raise run.failure(error) from error + finally: + finish() + result = run.result() + _log_warnings(result) + return result + + def _batch_attempt( + self, run: _BatchRun, headers: dict[str, str] + ) -> Callable[[], requests.Response]: + send = self._posthog_request( + "POST", _BATCH_PATH, run.body, headers, self._batch_timeout() + ) + retry = self._retry_while_admitted() + + def attempt() -> requests.Response: + retry() + try: + return send() + except requests.exceptions.RequestException: + run.lost() + raise + + return attempt + def _deliver(self, prepared: _PreparedSend, secret_key: str) -> SendEmailResult: if prepared.files: self._upload(prepared, secret_key) @@ -1754,7 +2451,12 @@ def get(self, message_id: Union[str, UUID]) -> EmailStatus: finish() def _posthog_request( - self, method: str, path: str, body: Optional[bytes], headers: dict[str, str] + self, + method: str, + path: str, + body: Optional[bytes], + headers: dict[str, str], + timeout: Optional[float] = None, ) -> Callable[[], requests.Response]: session, auth = self._get_session(), _BearerAuth(headers) return lambda: session.request( @@ -1762,7 +2464,7 @@ def _posthog_request( self.host + path, data=body, auth=auth, - timeout=self.timeout, + timeout=self.timeout if timeout is None else timeout, allow_redirects=False, ) @@ -1906,6 +2608,54 @@ async def send(self, **kwargs: Any) -> SendEmailResult: _log_warnings(result) return result + @overload + async def batch(self, **kwargs: Unpack[TemplateBatchArgs]) -> SendBatchResult: ... + + @overload + async def batch(self, **kwargs: Unpack[CodeBatchArgs]) -> SendBatchResult: ... + + async def batch(self, **kwargs: Any) -> SendBatchResult: + """Queue the same email for many recipients, one email each. + + Takes the same arguments, returns the same result and raises the same + errors as :meth:`Emails.batch`. + """ + run = _prepare_batch(kwargs) + finish = self._start(_SEND_NOT_DONE) + try: + secret_key = self._secret_key(_SEND_KEY_NEEDED) + headers = _headers(secret_key, self.migrated_from, has_body=True) + try: + await self._call( + self._batch_attempt(run, headers), run.answer, run.max_retries + ) + except EmailError as error: + raise run.failure(error) from error + finally: + finish() + result = run.result() + _log_warnings(result) + return result + + def _batch_attempt( + self, run: _BatchRun, headers: dict[str, str] + ) -> Callable[[], Awaitable[Any]]: + httpx, _ = self._get_client() + send = self._posthog_request( + "POST", _BATCH_PATH, run.body, headers, self._batch_timeout() + ) + retry = self._retry_while_admitted() + + async def attempt() -> Any: + retry() + try: + return await send() + except httpx.RequestError: + run.lost() + raise + + return attempt + async def _deliver( self, prepared: _PreparedSend, secret_key: str ) -> SendEmailResult: @@ -1959,7 +2709,12 @@ async def get(self, message_id: Union[str, UUID]) -> EmailStatus: finish() def _posthog_request( - self, method: str, path: str, body: Optional[bytes], headers: dict[str, str] + self, + method: str, + path: str, + body: Optional[bytes], + headers: dict[str, str], + timeout: Optional[float] = None, ) -> Callable[[], Awaitable[Any]]: _, client = self._get_client() # An injected client may carry its own auth and timeout, so set both per request: auth=None keeps @@ -1970,7 +2725,7 @@ def _posthog_request( content=body, headers=headers, auth=None, - timeout=self.timeout, + timeout=self.timeout if timeout is None else timeout, ) def _storage_request(self, upload: _Upload) -> Callable[[], Awaitable[Any]]: diff --git a/posthog/test/test_emails.py b/posthog/test/test_emails.py index a3dbc4292..174ff5360 100644 --- a/posthog/test/test_emails.py +++ b/posthog/test/test_emails.py @@ -3412,3 +3412,17 @@ async def test_async_refuses_a_naive_time_before_any_request(): ) assert seen == [] + + +def test_a_template_send_keeps_its_request_bytes(): + emails, adapter = emails_with([accepted()]) + + send(emails, template_data={"name": "Ada"}, distinct_id="user_1") + + assert ( + adapter.requests[0].body + == ( + f'{{"template_id": "{TEMPLATE_ID}", "to": "user@example.com", ' + '"message_data": {"name": "Ada"}, "distinct_id": "user_1"}' + ).encode() + ) diff --git a/posthog/test/test_emails_batch.py b/posthog/test/test_emails_batch.py new file mode 100644 index 000000000..25344061c --- /dev/null +++ b/posthog/test/test_emails_batch.py @@ -0,0 +1,1383 @@ +from __future__ import annotations + +import asyncio +import json +import logging +from typing import Any, Optional +from unittest import mock + +import httpx +import pytest +import requests +from parameterized import parameterized + +from posthog import AsyncPosthog, Posthog +from posthog.emails import ( + AsyncEmails, + EmailBatchError, + EmailError, + Emails, +) + +SECRET_KEY = "phs_test_secret" +TEMPLATE_ID = "0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b" +BATCH_URL = "https://us.posthog.com/api/messaging/send/email_batch/" + +Answer = Any # an Exception, or (status, body, headers) + + +class Slow: + """A server that answers after ``seconds``. A shorter wait times out.""" + + def __init__(self, seconds: float, answer: Answer) -> None: + self.seconds = seconds + self.answer = answer + + def within(self, waited: Optional[float], timed_out: Exception) -> Answer: + if waited is not None and waited < self.seconds: + return timed_out + return self.answer + + +def read_timeout(timeout: Any) -> Optional[float]: + return timeout[1] if isinstance(timeout, tuple) else timeout + + +class BatchPostHog(requests.adapters.BaseAdapter): + """Answers each request with the next answer, or with a callable of the request.""" + + def __init__(self, answers: list[Answer]) -> None: + super().__init__() + self.answers = list(answers) + self.requests: list[requests.PreparedRequest] = [] + + def send( + self, request: requests.PreparedRequest, **kwargs: Any + ) -> requests.Response: + self.requests.append(request) + answer = self.answers.pop(0) + if isinstance(answer, Slow): + answer = answer.within( + read_timeout(kwargs.get("timeout")), requests.ReadTimeout("timed out") + ) + if callable(answer): + answer = answer(request) + if isinstance(answer, Exception): + raise answer + status, body, headers = answer + reply = requests.Response() + reply.status_code = status + if isinstance(body, bytes): + reply._content = body + else: + reply._content = b"" if body is None else json.dumps(body).encode() + reply.headers.update(headers) + reply.request = request + return reply + + def close(self) -> None: + pass + + def batch_bodies(self) -> list[dict[str, Any]]: + return [ + json.loads(request.body) + for request in self.requests + if request.url == BATCH_URL + ] + + +def on_the_wire(posthog: BatchPostHog) -> Any: + def send( + adapter: requests.adapters.HTTPAdapter, + request: requests.PreparedRequest, + **kwargs: Any, + ) -> requests.Response: + return posthog.send(request, **kwargs) + + return mock.patch.object(requests.adapters.HTTPAdapter, "send", send) + + +def emails_on(answers: list[Answer], **options: Any) -> tuple[Emails, BatchPostHog]: + adapter = BatchPostHog(answers) + session = requests.Session() + session.mount("https://", adapter) + return Emails(SECRET_KEY, session=session, **options), adapter + + +def queued(message_id: str, replayed: bool = False) -> dict[str, Any]: + return {"message_id": message_id, "status": "queued", "replayed": replayed} + + +def refused( + message_id: str, code: str, status: int = 422, retryable: bool = False +) -> dict[str, Any]: + return { + "message_id": message_id, + "error": { + "code": code, + "detail": f"Refused: {code}.", + "status": status, + "retryable": retryable, + }, + } + + +def ok(*slots: dict[str, Any], **fields: Any) -> Answer: + return (200, {"results": list(slots), **fields}, {}) + + +def all_queued(request: requests.PreparedRequest) -> Answer: + keys = [r["idempotency_key"] for r in json.loads(request.body)["recipients"]] + return ok(*(queued(f"msg_{key}") for key in keys)) + + +def whole_call(status: int, code: Optional[str] = None, **headers: str) -> Answer: + body = ( + {"type": "invalid_request", "code": code, "detail": "Nope."} if code else None + ) + return (status, body, headers) + + +def recipients(count: int, **extra: Any) -> list[dict[str, Any]]: + return [ + {"to": f"user{i}@example.com", "idempotency_key": f"key-{i}", **extra} + for i in range(count) + ] + + +def batch(emails: Emails, people: list[dict[str, Any]], **overrides: Any): + return emails.batch( + **{"recipients": people, "template_id": TEMPLATE_ID, **overrides} + ) + + +@pytest.fixture(autouse=True) +def no_sleep(): + with ( + mock.patch("posthog.emails.time.sleep") as sleep, + mock.patch("posthog.emails.random.uniform", return_value=1.0), + ): + yield sleep + + +def test_a_template_batch_posts_one_request_with_a_result_per_recipient(): + emails, posthog = emails_on( + [ + ok( + queued("m0"), + queued("m1", replayed=True), + refused("m2", "recipient_suppressed"), + ) + ] + ) + + result = batch( + emails, + [ + {"to": "a@example.com", "idempotency_key": "welcome:a", "distinct_id": "a"}, + {"to": "b@example.com", "template_data": {"name": "Bea"}}, + {"to": "c@example.com", "idempotency_key": "welcome:c"}, + ], + template_data={"name": "friend", "plan": "pro"}, + ) + + [request] = posthog.requests + assert (request.method, request.url) == ("POST", BATCH_URL) + assert request.headers["Authorization"] == f"Bearer {SECRET_KEY}" + assert "Idempotency-Key" not in request.headers + body = json.loads(request.body) + generated = body["recipients"][1]["idempotency_key"] + assert body == { + "template_id": TEMPLATE_ID, + "message_data": {"name": "friend", "plan": "pro"}, + "recipients": [ + {"to": "a@example.com", "idempotency_key": "welcome:a", "distinct_id": "a"}, + { + "to": "b@example.com", + "idempotency_key": generated, + "message_data": {"name": "Bea"}, + }, + {"to": "c@example.com", "idempotency_key": "welcome:c"}, + ], + } + assert generated not in ("welcome:a", "welcome:c") + assert [r.index for r in result.results] == [0, 1, 2] + assert [r.idempotency_key for r in result.results] == [ + "welcome:a", + generated, + "welcome:c", + ] + assert [(r.status, r.message_id, r.replayed) for r in result.results] == [ + ("queued", "m0", False), + ("queued", "m1", True), + ("failed", "m2", False), + ] + error = result.results[2].error + assert isinstance(error, EmailError) + assert (error.code, error.status_code, error.message_id) == ( + "recipient_suppressed", + 422, + "m2", + ) + assert result.results[2].to == "c@example.com" + + +def test_a_code_batch_sends_the_same_content_to_every_recipient(): + emails, posthog = emails_on([all_queued]) + + result = emails.batch( + recipients=recipients(2), + template_key="launch-news", + subject="We launched", + html="Hi
", + from_="AcmeHi
", + "from": "AcmeHi
", + recipients=recipients(1), + ) + + error = raised.value + assert (error.code, error.status_code, error.field) == ("not_found", 404, None) + assert error.message == ( + "Batch sends or sending from code aren't available for this project, so " + "PostHog sent no email of this request." + ) + assert error.fix == ( + "If the project can send email from code, send each recipient on its own " + "with send() and its idempotency_key until batch sends are available." + ) + assert "template_id" not in " ".join( + filter(None, [error.message, error.why, error.fix]) + ) + assert_no_update_advice(error) + assert [r.status for r in raised.value.results] == ["failed"] + + +SEND_AGAIN = ( + "Send it again with the same idempotency_key within 24 hours of the first " + "request that used it, so it goes out once." +) + + +@pytest.mark.parametrize( + "form", + [ + {"template_id": TEMPLATE_ID}, + {"template_key": "digest", "subject": "Hi", "html": "Hi
"}, + ], + ids=["template", "code"], +) +@pytest.mark.parametrize( + "lost", [requests.ConnectionError("reset"), (503, None, {})], ids=["dropped", "503"] +) +def test_a_404_after_a_lost_answer_leaves_every_recipient_unconfirmed(form, lost): + body = { + "type": "invalid_request", + "code": "not_found", + "attr": None, + "detail": "Not found.", + } + emails, posthog = emails_on([lost, (404, body, {})]) + + with pytest.raises(EmailBatchError) as raised: + emails.batch(recipients=recipients(2), **form) + + error = raised.value + assert len(posthog.requests) == 2 + assert (error.code, error.status_code) == ("not_found", 404) + assert "sent no email" not in error.message + assert "may still go out" in error.message + assert [(r.status, r.idempotency_key) for r in error.results] == [ + ("unconfirmed", "key-0"), + ("unconfirmed", "key-1"), + ] + for result in error.results: + assert result.error is not None + assert result.error.fix == SEND_AGAIN + assert "sent no email" not in result.error.message + + +UNCONFIRMED = "PostHog didn't confirm this email, so it may still go out." +BATCH_UNCONFIRMED = ( + "PostHog didn't confirm this batch, so some of its emails may still go out." +) +SEND_EACH_AGAIN = ( + "Send each recipient again with the same idempotency_key within 24 hours of the " + "first request that used it, so each email goes out once, and read each " + "recipient's result." +) + + +@pytest.mark.parametrize( + "body", + [ + {"code": "conflict", "detail": "Conflict."}, + {"code": "api_error", "detail": "Something went wrong."}, + { + "code": "idempotency_key_reused", + "detail": "This key was used for another email.", + }, + ], + ids=["conflict", "api_error", "key_reused"], +) +def test_a_409_with_a_code_other_than_batch_unavailable_leaves_the_batch_unconfirmed( + body, +): + emails, _ = emails_on([(409, body, {})]) + + with pytest.raises(EmailBatchError) as raised: + batch(emails, recipients(2)) + + error = raised.value + assert (error.status_code, error.code) == (409, body["code"]) + assert error.fix == SEND_EACH_AGAIN + assert [(r.status, r.idempotency_key) for r in error.results] == [ + ("unconfirmed", "key-0"), + ("unconfirmed", "key-1"), + ] + assert all(r.error is not None and r.error.fix == SEND_AGAIN for r in error.results) + + +@pytest.mark.parametrize( + "status, body", + [ + ( + 400, + { + "code": "content_too_large", + "detail": "The template_data is too large, so PostHog didn't send it.", + }, + ), + (404, {"code": "not_found", "detail": "Not found."}), + ( + 409, + { + "code": "batch_unavailable", + "detail": "Batch sends aren't on, so nothing was sent.", + }, + ), + ( + 413, + { + "code": "content_too_large", + "detail": "The batch is larger than PostHog can send at once, so PostHog didn't send it.", + "fix": "Split the recipients into smaller batches.", + }, + ), + ], + ids=["400", "404", "409_batch_unavailable", "413"], +) +def test_a_refused_retry_after_a_lost_answer_never_says_nothing_was_sent(status, body): + emails, posthog = emails_on([requests.ConnectionError("reset"), (status, body, {})]) + + with pytest.raises(EmailBatchError) as raised: + batch(emails, recipients(2)) + + error = raised.value + assert len(posthog.requests) == 2 + assert (error.status_code, error.code) == (status, body["code"]) + assert error.message == BATCH_UNCONFIRMED + assert error.fix == SEND_EACH_AGAIN + said = " ".join(filter(None, [error.message, error.why, error.fix])).lower() + assert "split" not in said and "didn't send" not in said and "nothing" not in said + assert [(r.status, r.idempotency_key) for r in error.results] == [ + ("unconfirmed", "key-0"), + ("unconfirmed", "key-1"), + ] + + +@pytest.mark.parametrize( + "answers", + [ + pytest.param([requests.ConnectionError("reset")] * 4, id="network"), + pytest.param( + [(503, {"code": "delivery_unavailable", "detail": "Delivery failed."}, {})] + * 4, + id="503", + ), + pytest.param( + [ok(refused("m0", "idempotency_key_in_flight", status=409), queued("m1"))], + id="in_flight_slot", + ), + pytest.param( + [ok({"message_id": "m0", "error": {"code": "api_error"}}, queued("m1"))], + id="api_error_slot_without_detail", + ), + pytest.param( + [ + requests.ConnectionError("reset"), + ok(refused("m0", "invalid_recipient"), queued("m1")), + ], + id="refused_slot_after_a_lost_answer", + ), + ], +) +def test_an_unconfirmed_recipient_is_never_told_its_email_was_not_sent(answers): + emails, _ = emails_on(answers) + + try: + results = batch(emails, recipients(2)).results + except EmailBatchError as raised: + results = raised.results + + unconfirmed = [r for r in results if r.status == "unconfirmed"] + assert unconfirmed + for result in unconfirmed: + assert result.error is not None + assert result.error.message == UNCONFIRMED + said = " ".join(filter(None, [result.error.message, result.error.why])).lower() + for words in ( + "not queued", + "didn't queue", + "not sent", + "didn't send", + "failed", + ): + assert words not in said + + +def test_a_404_that_names_a_field_keeps_what_posthog_said(): + body = {"code": "not_found", "attr": "template_id", "detail": "No such template."} + emails, _ = emails_on([(404, body, {})]) + + with pytest.raises(EmailBatchError) as raised: + batch(emails, recipients(1)) + + error = raised.value + assert (error.code, error.field, error.message) == ( + "not_found", + "template_id", + "No such template.", + ) + assert_no_update_advice(error) + + +def test_an_answer_without_a_result_per_recipient_leaves_the_batch_unconfirmed(): + emails, posthog = emails_on([ok(queued("m0"))]) + + with pytest.raises(EmailBatchError) as raised: + batch(emails, recipients(2), max_retries=0) + + assert raised.value.code == "api_error" + assert [r.status for r in raised.value.results] == ["unconfirmed", "unconfirmed"] + assert [r.url for r in posthog.requests] == [BATCH_URL] + + +def test_warnings_reach_the_caller_once(caplog): + warning = {"code": "sandbox_sender", "detail": "Sent from the test sender."} + + def queued_with_warning(request: requests.PreparedRequest) -> Answer: + status, body, headers = all_queued(request) + return status, {**body, "warnings": [warning, warning]}, headers + + emails, _ = emails_on([queued_with_warning]) + + with caplog.at_level(logging.WARNING, logger="posthog"): + result = batch(emails, recipients(2)) + + assert [w.code for w in result.warnings] == ["sandbox_sender"] + assert caplog.text.count("sandbox_sender") == 1 + + +def test_a_disabled_client_sends_nothing(): + emails, posthog = emails_on([], disabled=True) + + with pytest.raises(EmailError) as disabled: + batch(emails, recipients(1)) + + assert disabled.value.code == "client_disabled" + assert posthog.requests == [] + + +def test_a_client_off_cloud_without_an_app_host_sends_nothing(): + client = Posthog( + "phc_test", host="https://ph.example.com", secret_key=SECRET_KEY, sync_mode=True + ) + posthog = BatchPostHog([]) + + with on_the_wire(posthog), pytest.raises(EmailError) as no_host: + batch(client.emails, recipients(1)) + + assert no_host.value.code == "missing_app_host" + assert posthog.requests == [] + + +def test_a_refused_recipient_field_names_its_position_in_recipients(): + emails, _ = emails_on( + [ + ( + 400, + { + "type": "validation_error", + "code": "invalid", + "detail": "Enter a valid email address.", + "attr": "recipients__1__to", + }, + {}, + ), + ] + ) + + with pytest.raises(EmailBatchError) as raised: + batch(emails, recipients(2)) + + assert raised.value.field == "recipients__1__to" + assert [r.status for r in raised.value.results] == ["failed", "failed"] + + +def test_a_code_batch_without_content_names_batch(): + emails, posthog = emails_on([]) + + with pytest.raises(TypeError, match=r"batch\(\) needs html, text or both"): + emails.batch(template_key="digest", subject="Hi", recipients=recipients(1)) + + assert posthog.requests == [] + + +def async_emails_on( + answers: list[Any], **options: Any +) -> tuple[AsyncEmails, list[httpx.Request]]: + seen: list[httpx.Request] = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append(request) + answer = answers.pop(0) + if isinstance(answer, Slow): + answer = answer.within( + request.extensions["timeout"]["read"], httpx.ReadTimeout("timed out") + ) + if callable(answer): + answer = answer(request) + if isinstance(answer, Exception): + raise answer + return answer + + client = httpx.AsyncClient(transport=httpx.MockTransport(handler)) + return AsyncEmails(SECRET_KEY, http_client=client, **options), seen + + +def async_all_queued(request: httpx.Request) -> httpx.Response: + keys = [r["idempotency_key"] for r in json.loads(request.content)["recipients"]] + return httpx.Response(200, json={"results": [queued(f"m-{k}") for k in keys]}) + + +@pytest.mark.asyncio +async def test_async_batch_sends_100_recipients_in_one_request(): + emails, seen = async_emails_on([async_all_queued]) + + result = await emails.batch(recipients=recipients(100), template_id=TEMPLATE_ID) + + assert [len(json.loads(r.content)["recipients"]) for r in seen] == [100] + assert [r.status for r in result.results] == ["queued"] * 100 + + +@pytest.mark.asyncio +async def test_async_batch_refuses_more_than_100_recipients_before_any_request(): + emails, seen = async_emails_on([]) + + with pytest.raises(ValueError, match="at most 100 recipients"): + await emails.batch(recipients=recipients(101), template_id=TEMPLATE_ID) + + assert seen == [] + + +@pytest.mark.asyncio +async def test_async_batch_keeps_a_recipient_unconfirmed_after_a_lost_answer(): + emails, _ = async_emails_on( + [ + httpx.ConnectError("reset"), + httpx.Response(200, json={"results": [refused("m-0", "sending_paused")]}), + ] + ) + + with mock.patch("posthog.emails.asyncio.sleep"): + result = await emails.batch(recipients=recipients(1), template_id=TEMPLATE_ID) + + [only] = result.results + assert only.status == "unconfirmed" + assert only.error is not None and only.error.code == "sending_paused" + + +@pytest.mark.asyncio +async def test_async_batch_waits_for_a_slow_answer_whatever_the_client_timeout(): + emails, _ = async_emails_on([Slow(40, async_all_queued)], timeout=3) + + result = await emails.batch(recipients=recipients(1), template_id=TEMPLATE_ID) + + assert [r.status for r in result.results] == ["queued"] + + +@pytest.mark.asyncio +async def test_async_batch_reads_no_lost_email_back(): + emails, seen = async_emails_on([httpx.ConnectError("reset")]) + + with pytest.raises(EmailBatchError) as raised: + await emails.batch( + recipients=recipients(1), template_id=TEMPLATE_ID, max_retries=0 + ) + + assert raised.value.code == "network_error" + assert [(r.status, r.message_id) for r in raised.value.results] == [ + ("unconfirmed", None) + ] + assert [str(r.url) for r in seen] == [BATCH_URL] + + +@pytest.mark.asyncio +async def test_async_batch_that_succeeds_reads_no_unconfirmed_email_back(): + unconfirmed_slot = { + "error": { + "code": "delivery_unavailable", + "detail": "Not confirmed.", + "status": 503, + "retryable": True, + } + } + emails, seen = async_emails_on( + [httpx.Response(200, json={"results": [unconfirmed_slot]})] + ) + + result = await emails.batch( + recipients=recipients(1), template_id=TEMPLATE_ID, max_retries=0 + ) + + assert [(r.status, r.message_id) for r in result.results] == [("unconfirmed", None)] + assert [str(r.url) for r in seen] == [BATCH_URL] + + +@pytest.mark.asyncio +async def test_async_shutdown_during_a_retry_wait_sends_no_retry(): + client = AsyncPosthog("phc_test", secret_key=SECRET_KEY) + seen: list[httpx.Request] = [] + waits: list[float] = [] + real_sleep = asyncio.sleep + + async def wire( + transport: httpx.AsyncHTTPTransport, request: httpx.Request + ) -> httpx.Response: + seen.append(request) + if waits: + return async_all_queued(request) + return httpx.Response(429) + + shutting_down: list[asyncio.Task[None]] = [] + + async def shutdown_during_the_wait(delay: float) -> None: + if waits: + await real_sleep(0) + return + waits.append(delay) + shutting_down.append(asyncio.create_task(client.shutdown())) + for _ in range(5): + await real_sleep(0) + + with ( + mock.patch.object(httpx.AsyncHTTPTransport, "handle_async_request", wire), + mock.patch("posthog.emails.asyncio.sleep", new=shutdown_during_the_wait), + pytest.raises(EmailBatchError) as raised, + ): + await client.emails.batch(recipients=recipients(2), template_id=TEMPLATE_ID) + await shutting_down[0] + + assert raised.value.code == "client_closed" + assert len(seen) == 1 + assert [r.status for r in raised.value.results] == ["failed", "failed"] diff --git a/references/public_api_snapshot.txt b/references/public_api_snapshot.txt index 6fa86ff6c..1bf6894d1 100644 --- a/references/public_api_snapshot.txt +++ b/references/public_api_snapshot.txt @@ -917,6 +917,26 @@ attribute posthog.debug = False attribute posthog.default_client = None attribute posthog.disable_geoip = True attribute posthog.disabled = False +attribute posthog.emails.BatchEmailResult.error: Optional[EmailError] = None +attribute posthog.emails.BatchEmailResult.idempotency_key: str +attribute posthog.emails.BatchEmailResult.index: int +attribute posthog.emails.BatchEmailResult.message_id: Optional[str] = None +attribute posthog.emails.BatchEmailResult.replayed: bool = False +attribute posthog.emails.BatchEmailResult.status: BatchStatus +attribute posthog.emails.BatchEmailResult.to: str +attribute posthog.emails.BatchRecipient.distinct_id: NotRequired[Optional[str]] +attribute posthog.emails.BatchRecipient.idempotency_key: NotRequired[Optional[str]] +attribute posthog.emails.BatchRecipient.template_data: NotRequired[Optional[Mapping[str, Any]]] +attribute posthog.emails.BatchRecipient.to: str +attribute posthog.emails.CodeBatchArgs.capture_engagement: NotRequired[Optional[bool]] +attribute posthog.emails.CodeBatchArgs.from_: NotRequired[Optional[str]] +attribute posthog.emails.CodeBatchArgs.html: NotRequired[Optional[str]] +attribute posthog.emails.CodeBatchArgs.reply_to: NotRequired[Optional[Union[str, Sequence[str]]]] +attribute posthog.emails.CodeBatchArgs.sensitive: NotRequired[Optional[bool]] +attribute posthog.emails.CodeBatchArgs.subject: str +attribute posthog.emails.CodeBatchArgs.template_key: str +attribute posthog.emails.CodeBatchArgs.text: NotRequired[Optional[str]] +attribute posthog.emails.CodeBatchArgs.tracking: NotRequired[Optional[Union[bool, EmailTracking]]] attribute posthog.emails.CodeEmailArgs.attachments: NotRequired[Optional[Sequence[EmailAttachment]]] attribute posthog.emails.CodeEmailArgs.bcc: NotRequired[Optional[Union[str, Sequence[str]]]] attribute posthog.emails.CodeEmailArgs.capture_engagement: NotRequired[Optional[bool]] @@ -933,6 +953,7 @@ attribute posthog.emails.EmailAttachment.content: Union[bytes, bytearray, memory attribute posthog.emails.EmailAttachment.content_id: NotRequired[str] attribute posthog.emails.EmailAttachment.content_type: NotRequired[str] attribute posthog.emails.EmailAttachment.filename: str +attribute posthog.emails.EmailBatchError.results = results attribute posthog.emails.EmailError.code = code attribute posthog.emails.EmailError.docs_url = docs_url attribute posthog.emails.EmailError.field = field @@ -954,11 +975,15 @@ attribute posthog.emails.EmailTracking.opens: bool attribute posthog.emails.EmailWarning.code: str attribute posthog.emails.EmailWarning.fix: Optional[str] = None attribute posthog.emails.EmailWarning.message: str +attribute posthog.emails.SendBatchResult.results: tuple[BatchEmailResult, ...] +attribute posthog.emails.SendBatchResult.warnings: tuple[EmailWarning, ...] = () attribute posthog.emails.SendEmailResult.id: str attribute posthog.emails.SendEmailResult.replayed: bool = False attribute posthog.emails.SendEmailResult.scheduled_at: Optional[datetime] = None attribute posthog.emails.SendEmailResult.status: Literal['queued', 'scheduled'] attribute posthog.emails.SendEmailResult.warnings: tuple[EmailWarning, ...] = () +attribute posthog.emails.TemplateBatchArgs.template_data: NotRequired[Optional[Mapping[str, Any]]] +attribute posthog.emails.TemplateBatchArgs.template_id: Union[str, UUID] attribute posthog.emails.TemplateEmailArgs.template_data: NotRequired[Optional[Mapping[str, Any]]] attribute posthog.emails.TemplateEmailArgs.template_id: Union[str, UUID] attribute posthog.enable_exception_autocapture = False @@ -1395,14 +1420,20 @@ class posthog.client.Client(project_api_key: str, host=None, *, debug=False, max class posthog.consumer.Consumer(queue, api_key, flush_at=100, host=None, on_error=None, flush_interval=5.0, retries=3, timeout: float = 15, historical_migration=False, endpoint=_CAPTURE_V1_PATH, max_msg_size=MAX_MSG_SIZE, capture_compression=CaptureCompression.NONE) class posthog.contexts.ContextScope(parent=None, fresh: bool = False, capture_exceptions: bool = True, client: Optional[Client] = None) class posthog.emails.AsyncEmails(secret_key: Optional[str], *, host: Optional[str] = None, timeout: float = 15, max_retries: int = 2, disabled: bool = False, http_client: Any = None, migrated_from: Optional[str] = None) +class posthog.emails.BatchEmailResult(index: int, to: str, idempotency_key: str, status: BatchStatus, message_id: Optional[str] = None, replayed: bool = False, error: Optional[EmailError] = None) +class posthog.emails.BatchRecipient +class posthog.emails.CodeBatchArgs class posthog.emails.CodeEmailArgs class posthog.emails.EmailAttachment +class posthog.emails.EmailBatchError(error: EmailError, results: tuple[BatchEmailResult, ...]) class posthog.emails.EmailError(*, name: str, code: str, message: str, status_code: Optional[int] = None, why: Optional[str] = None, fix: Optional[str] = None, docs_url: Optional[str] = None, field: Optional[str] = None, retry_after: Optional[float] = None, message_id: Optional[str] = None) class posthog.emails.EmailStatus(id: str, status: str, created_at: datetime, status_at: datetime, reason: Optional[str] = None) class posthog.emails.EmailTracking class posthog.emails.EmailWarning(code: str, message: str, fix: Optional[str] = None) class posthog.emails.Emails(secret_key: Optional[str], *, host: Optional[str] = None, timeout: float = 15, max_retries: int = 2, disabled: bool = False, session: Optional[requests.Session] = None, migrated_from: Optional[str] = None) +class posthog.emails.SendBatchResult(results: tuple[BatchEmailResult, ...], warnings: tuple[EmailWarning, ...] = ()) class posthog.emails.SendEmailResult(id: str, replayed: bool = False, warnings: tuple[EmailWarning, ...] = (), scheduled_at: Optional[datetime] = None) +class posthog.emails.TemplateBatchArgs class posthog.emails.TemplateEmailArgs class posthog.exception_capture.ExceptionCapture(client: Client, rate_limiting_enabled=False, bucket_size=DEFAULT_BUCKET_SIZE, refill_rate=DEFAULT_REFILL_RATE, refill_interval_seconds=DEFAULT_REFILL_INTERVAL_SECONDS) class posthog.exception_utils.AnnotatedValue(value, metadata) @@ -1934,8 +1965,10 @@ method posthog.contexts.ContextScope.set_device_id(device_id: str) method posthog.contexts.ContextScope.set_distinct_id(distinct_id: str) method posthog.contexts.ContextScope.set_session_id(session_id: str) method posthog.emails.AsyncEmails.aclose() -> None +method posthog.emails.AsyncEmails.batch(**kwargs: Any) -> SendBatchResult method posthog.emails.AsyncEmails.get(message_id: Union[str, UUID]) -> EmailStatus method posthog.emails.AsyncEmails.send(**kwargs: Any) -> SendEmailResult +method posthog.emails.Emails.batch(**kwargs: Any) -> SendBatchResult method posthog.emails.Emails.close() -> None method posthog.emails.Emails.get(message_id: Union[str, UUID]) -> EmailStatus method posthog.emails.Emails.send(**kwargs: Any) -> SendEmailResult