From dbd27e14f042989291ecbe40645f88906b6ebcb4 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:21:31 +0100 Subject: [PATCH 01/44] test(emails): split the compatibility test, check a send without scheduled_at Co-Authored-By: Claude Opus 5.5 --- test/EmailsTest.php | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/test/EmailsTest.php b/test/EmailsTest.php index c6c3bc5..f011b88 100644 --- a/test/EmailsTest.php +++ b/test/EmailsTest.php @@ -2136,18 +2136,34 @@ private static function errorSerializedBeforeScheduling(): string ); } - public function testAResultOrErrorSerializedByTheVersionBeforeSchedulingStillReads(): void + public function testAResultSerializedByTheVersionBeforeSchedulingStillReads(): void { $result = unserialize(self::resultSerializedBeforeScheduling()); - $error = unserialize(self::errorSerializedBeforeScheduling()); $this->assertSame('msg_1', $result->getId()); $this->assertSame('queued', $result->getStatus()); $this->assertNull($result->getScheduledAt()); + } + + public function testAnErrorSerializedByTheVersionBeforeSchedulingStillReads(): void + { + $error = unserialize(self::errorSerializedBeforeScheduling()); + $this->assertSame('throttled', $error->getErrorCode()); $this->assertNull($error->getMessageId()); } + public function testASendWithoutScheduledAtIgnoresAScheduleInTheAnswer(): void + { + $this->reply(self::scheduledReply('2026-11-03T09:00:00.000Z')); + + $result = $this->emails()->send(['to' => 'user@example.com', 'template_id' => self::TEMPLATE_ID]); + + $this->assertArrayNotHasKey('scheduled_at', $this->body()); + $this->assertSame('queued', $result->getStatus()); + $this->assertNull($result->getScheduledAt()); + } + public function testBadClientOptionsAreRefused(): void { foreach ( From 90c013abb4a397592b17c3ac5e296462e105e674 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:28:30 +0100 Subject: [PATCH 02/44] test(emails): share the email client fixture and request helpers in a trait Co-Authored-By: Claude Opus 5.5 --- test/EmailsTest.php | 84 +--------------------------------- test/EmailsTestSupport.php | 93 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+), 82 deletions(-) create mode 100644 test/EmailsTestSupport.php diff --git a/test/EmailsTest.php b/test/EmailsTest.php index f011b88..2aff644 100644 --- a/test/EmailsTest.php +++ b/test/EmailsTest.php @@ -17,19 +17,14 @@ class EmailsTest extends TestCase { + use EmailsTestSupport; + private const TEMPLATE_ID = '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b'; private const MESSAGE_ID = '01a18356-c56c-0001-e494-7666bc915188'; private const SEND_URL = 'https://us.posthog.com/api/messaging/send/email/'; private const INVITE = "BEGIN:VCALENDAR\r\nEND:VCALENDAR\r\n"; private const SECRET_CONTENT = 'secret-file-content'; - /** - * @var list, body: ?string, timeoutMs: int, - * at: DateTimeImmutable}> - */ - private array $requests = []; - /** @var list}|EmailError|string> */ - private array $replies = []; /** @var array> the headers storage signed for each upload URL */ private array $signedUploads = []; /** @var array the files storage holds, by SHA-256; null for one PostHog already had */ @@ -38,42 +33,6 @@ class EmailsTest extends TestCase private array $storageWrites = []; /** @var array> the emails PostHog queued, one per idempotency key */ private array $queued = []; - private string $secretKey = 'phs_secret'; - private ClockInterface $previousClock; - private MockClock $clock; - - protected function setUp(): void - { - require_once __DIR__ . '/error_log_mock.php'; - global $errorMessages; - $errorMessages = []; - $this->previousClock = Clock::get(); - $this->clock = new MockClock('2026-11-02 12:00:00'); - Clock::set($this->clock); - } - - protected function tearDown(): void - { - Clock::set($this->previousClock); - } - - private function emails(array $config = []): Emails - { - $this->secretKey = $config['secretKey'] ?? 'phs_secret'; - - return new Emails( - $this->secretKey, - $config['host'] ?? 'us.i.posthog.com', - appHost: $config['appHost'] ?? null, - maxRetries: $config['maxRetries'] ?? Emails::DEFAULT_MAX_RETRIES, - migratedFrom: $config['migratedFrom'] ?? null, - userAgent: 'posthog-php/9.9.9', - isDisabled: $config['isDisabled'] ?? null, - isClosed: $config['isClosed'] ?? null, - transport: Closure::fromCallable([$this, 'transport']) - ); - } - /** * @param list $headers * @return array{int, string, list} @@ -152,18 +111,6 @@ private function negotiate(string $body): array return self::slots(...$slots); } - /** @param list $headers */ - private static function headerIn(array $headers, string $name): ?string - { - foreach ($headers as $header) { - if (stripos($header, $name . ':') === 0) { - return trim(substr($header, strlen($name) + 1)); - } - } - - return null; - } - /** The reference of the first attachment storage doesn't hold, as PostHog names it, or null. */ private function notStored(string $body): ?string { @@ -215,33 +162,6 @@ private static function storageAccepts(array $headers, string $body): bool return true; } - /** @param array{int, string, list}|EmailError|string ...$replies */ - private function reply(...$replies): void - { - $this->replies = $replies; - } - - private function body(int $index = 0): array - { - return json_decode($this->requests[$index]['body'], true, 512, JSON_THROW_ON_ERROR); - } - - private function header(string $name, int $index = 0): ?string - { - foreach ($this->requests[$index]['headers'] as $header) { - if (stripos($header, $name . ':') === 0) { - return trim(substr($header, strlen($name) + 1)); - } - } - - return null; - } - - private static function msBetween(DateTimeImmutable $start, DateTimeImmutable $end): int - { - return (int) round(((float) $end->format('U.u') - (float) $start->format('U.u')) * 1000); - } - private function sendError(array $email, ?Emails $emails = null): EmailError { try { diff --git a/test/EmailsTestSupport.php b/test/EmailsTestSupport.php new file mode 100644 index 0000000..ecfe182 --- /dev/null +++ b/test/EmailsTestSupport.php @@ -0,0 +1,93 @@ +, body: ?string, timeoutMs: int, + * at: DateTimeImmutable}> + */ + private array $requests = []; + /** @var list */ + private array $replies = []; + private string $secretKey = 'phs_secret'; + private ClockInterface $previousClock; + private MockClock $clock; + + protected function setUp(): void + { + require_once __DIR__ . '/error_log_mock.php'; + global $errorMessages; + $errorMessages = []; + $this->previousClock = Clock::get(); + $this->clock = new MockClock('2026-11-02 12:00:00'); + Clock::set($this->clock); + } + + protected function tearDown(): void + { + Clock::set($this->previousClock); + } + + private function emails(array $config = []): Emails + { + $this->secretKey = $config['secretKey'] ?? 'phs_secret'; + + return new Emails( + $this->secretKey, + $config['host'] ?? 'us.i.posthog.com', + appHost: $config['appHost'] ?? null, + requestTimeoutMs: $config['requestTimeoutMs'] ?? Emails::DEFAULT_REQUEST_TIMEOUT_MS, + maxRetries: $config['maxRetries'] ?? Emails::DEFAULT_MAX_RETRIES, + migratedFrom: $config['migratedFrom'] ?? null, + userAgent: 'posthog-php/9.9.9', + isDisabled: $config['isDisabled'] ?? null, + isClosed: $config['isClosed'] ?? null, + transport: Closure::fromCallable([$this, 'transport']) + ); + } + + private function reply(mixed ...$replies): void + { + $this->replies = $replies; + } + + private function body(int $index = 0): array + { + return json_decode($this->requests[$index]['body'], true, 512, JSON_THROW_ON_ERROR); + } + + private function header(string $name, int $index = 0): ?string + { + return self::headerIn($this->requests[$index]['headers'], $name); + } + + /** @param list $headers */ + private static function headerIn(array $headers, string $name): ?string + { + foreach ($headers as $header) { + if (stripos($header, $name . ':') === 0) { + return trim(substr($header, strlen($name) + 1)); + } + } + + return null; + } + + private static function msBetween(DateTimeImmutable $start, DateTimeImmutable $end): int + { + return (int) round(((float) $end->format('U.u') - (float) $start->format('U.u')) * 1000); + } +} From 2da67f3954a9e6e831368276178d3619013de163 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:46:50 +0100 Subject: [PATCH 03/44] feat(emails): send one email to each of many recipients with emails()->batch() emails()->batch() takes a template or code-form email and a list of recipients, sends them in requests of at most 100 recipients and 4 MiB, one after another, and returns a result per recipient in input order: queued, failed, unconfirmed or not_attempted. Each recipient's idempotency key is given or generated and reused on every retry. A request that fails as a whole throws EmailBatchError with every recipient's result, after reading lost emails by their key. The reply parsing moves to Internal\EmailReplies and the recipient checks to Internal\EmailRecipient, so send() and batch() share them. Co-Authored-By: Claude Opus 5.5 --- .changeset/email-batch-sends.md | 5 + api/public-api.json | 295 +++++++++++ lib/BatchEmailResult.php | 102 ++++ lib/EmailBatchError.php | 54 ++ lib/EmailError.php | 11 +- lib/Emails.php | 401 ++++++++++----- lib/Internal/EmailBatch.php | 479 ++++++++++++++++++ lib/Internal/EmailRecipient.php | 56 +++ lib/Internal/EmailReplies.php | 113 +++++ lib/SendBatchResult.php | 38 ++ test/EmailsBatchTest.php | 860 ++++++++++++++++++++++++++++++++ 11 files changed, 2274 insertions(+), 140 deletions(-) create mode 100644 .changeset/email-batch-sends.md create mode 100644 lib/BatchEmailResult.php create mode 100644 lib/EmailBatchError.php create mode 100644 lib/Internal/EmailBatch.php create mode 100644 lib/Internal/EmailRecipient.php create mode 100644 lib/Internal/EmailReplies.php create mode 100644 lib/SendBatchResult.php create mode 100644 test/EmailsBatchTest.php diff --git a/.changeset/email-batch-sends.md b/.changeset/email-batch-sends.md new file mode 100644 index 0000000..923f36a --- /dev/null +++ b/.changeset/email-batch-sends.md @@ -0,0 +1,5 @@ +--- +"posthog-php": minor +--- + +Transactional email: `emails()->batch()` sends the same email to many recipients, one email each, from a template with `template_data` per recipient or from content in your code. The client sends at most 100 recipients and 4 MiB per request, one request after another, gives each recipient an idempotency key that every retry reuses, and returns a `SendBatchResult` with a `BatchEmailResult` per recipient: `queued`, `failed`, `unconfirmed` or `not_attempted`. A request that fails as a whole throws `EmailBatchError` with every recipient's result. diff --git a/api/public-api.json b/api/public-api.json index 985e28a..2f14e9d 100644 --- a/api/public-api.json +++ b/api/public-api.json @@ -2,6 +2,162 @@ "schemaVersion": 1, "namespace": "PostHog\\", "symbols": { + "PostHog\\BatchEmailResult": { + "type": "class", + "abstract": false, + "final": false, + "readonly": false, + "extends": null, + "implements": [], + "constants": [], + "properties": [], + "methods": { + "__construct": { + "static": false, + "abstract": false, + "final": false, + "returnType": null, + "parameters": [ + { + "name": "index", + "type": "int", + "byReference": false, + "variadic": false, + "optional": false, + "default": null, + "defaultConstant": null, + "hasDefault": false + }, + { + "name": "to", + "type": "string", + "byReference": false, + "variadic": false, + "optional": false, + "default": null, + "defaultConstant": null, + "hasDefault": false + }, + { + "name": "idempotencyKey", + "type": "string", + "byReference": false, + "variadic": false, + "optional": false, + "default": null, + "defaultConstant": null, + "hasDefault": false + }, + { + "name": "status", + "type": "string", + "byReference": false, + "variadic": false, + "optional": false, + "default": null, + "defaultConstant": null, + "hasDefault": false + }, + { + "name": "messageId", + "type": "?string", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true + }, + { + "name": "replayed", + "type": "bool", + "byReference": false, + "variadic": false, + "optional": true, + "default": false, + "defaultConstant": null, + "hasDefault": true + }, + { + "name": "error", + "type": "?PostHog\\EmailError", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true + }, + { + "name": "laterError", + "type": "?PostHog\\EmailError", + "byReference": false, + "variadic": false, + "optional": true, + "default": null, + "defaultConstant": null, + "hasDefault": true + } + ] + }, + "getError": { + "static": false, + "abstract": false, + "final": false, + "returnType": "?PostHog\\EmailError", + "parameters": [] + }, + "getIdempotencyKey": { + "static": false, + "abstract": false, + "final": false, + "returnType": "string", + "parameters": [] + }, + "getIndex": { + "static": false, + "abstract": false, + "final": false, + "returnType": "int", + "parameters": [] + }, + "getLaterError": { + "static": false, + "abstract": false, + "final": false, + "returnType": "?PostHog\\EmailError", + "parameters": [] + }, + "getMessageId": { + "static": false, + "abstract": false, + "final": false, + "returnType": "?string", + "parameters": [] + }, + "getStatus": { + "static": false, + "abstract": false, + "final": false, + "returnType": "string", + "parameters": [] + }, + "getTo": { + "static": false, + "abstract": false, + "final": false, + "returnType": "string", + "parameters": [] + }, + "isReplayed": { + "static": false, + "abstract": false, + "final": false, + "returnType": "bool", + "parameters": [] + } + } + }, "PostHog\\Client": { "type": "class", "abstract": false, @@ -1695,6 +1851,73 @@ } } }, + "PostHog\\EmailBatchError": { + "type": "class", + "abstract": false, + "final": false, + "readonly": false, + "extends": "PostHog\\EmailError", + "implements": [ + "Stringable", + "Throwable" + ], + "constants": [], + "properties": [], + "methods": { + "__construct": { + "static": false, + "abstract": false, + "final": false, + "returnType": null, + "parameters": [ + { + "name": "error", + "type": "PostHog\\EmailError", + "byReference": false, + "variadic": false, + "optional": false, + "default": null, + "defaultConstant": null, + "hasDefault": false + }, + { + "name": "results", + "type": "array", + "byReference": false, + "variadic": false, + "optional": false, + "default": null, + "defaultConstant": null, + "hasDefault": false + }, + { + "name": "warnings", + "type": "array", + "byReference": false, + "variadic": false, + "optional": true, + "default": [], + "defaultConstant": null, + "hasDefault": true + } + ] + }, + "getResults": { + "static": false, + "abstract": false, + "final": false, + "returnType": "array", + "parameters": [] + }, + "getWarnings": { + "static": false, + "abstract": false, + "final": false, + "returnType": "array", + "parameters": [] + } + } + }, "PostHog\\EmailError": { "type": "class", "abstract": false, @@ -2184,6 +2407,24 @@ } ] }, + "batch": { + "static": false, + "abstract": false, + "final": false, + "returnType": "PostHog\\SendBatchResult", + "parameters": [ + { + "name": "batch", + "type": "array", + "byReference": false, + "variadic": false, + "optional": false, + "default": null, + "defaultConstant": null, + "hasDefault": false + } + ] + }, "get": { "static": false, "abstract": false, @@ -5526,6 +5767,60 @@ } } }, + "PostHog\\SendBatchResult": { + "type": "class", + "abstract": false, + "final": false, + "readonly": false, + "extends": null, + "implements": [], + "constants": [], + "properties": [], + "methods": { + "__construct": { + "static": false, + "abstract": false, + "final": false, + "returnType": null, + "parameters": [ + { + "name": "results", + "type": "array", + "byReference": false, + "variadic": false, + "optional": false, + "default": null, + "defaultConstant": null, + "hasDefault": false + }, + { + "name": "warnings", + "type": "array", + "byReference": false, + "variadic": false, + "optional": true, + "default": [], + "defaultConstant": null, + "hasDefault": true + } + ] + }, + "getResults": { + "static": false, + "abstract": false, + "final": false, + "returnType": "array", + "parameters": [] + }, + "getWarnings": { + "static": false, + "abstract": false, + "final": false, + "returnType": "array", + "parameters": [] + } + } + }, "PostHog\\SendEmailResult": { "type": "class", "abstract": false, diff --git a/lib/BatchEmailResult.php b/lib/BatchEmailResult.php new file mode 100644 index 0000000..be3fdb0 --- /dev/null +++ b/lib/BatchEmailResult.php @@ -0,0 +1,102 @@ +index; + } + + /** + * The recipient's email address. + */ + public function getTo(): string + { + return $this->to; + } + + /** + * The recipient's idempotency key, given or made by the client. Send the email again with this key to make + * sure it goes out once. + */ + public function getIdempotencyKey(): string + { + return $this->idempotencyKey; + } + + /** + * `queued`, `failed`, `unconfirmed` or `not_attempted`. + */ + public function getStatus(): string + { + return $this->status; + } + + /** + * The email's message ID when PostHog named it, also for some emails it didn't queue. Pass it to + * Emails::get() to read the email's status. + */ + public function getMessageId(): ?string + { + return $this->messageId; + } + + /** + * True when an earlier send with the same idempotency key had already queued the email, so no new email was + * sent. + */ + public function isReplayed(): bool + { + return $this->replayed; + } + + /** + * Why the email is not `queued`, or null when it is. For an `unconfirmed` email, the code is + * `delivery_unavailable`, `idempotency_key_in_flight` or `api_error`. + */ + public function getError(): ?EmailError + { + return $this->error; + } + + /** + * For an `unconfirmed` email, what a later attempt in the same call answered, such as `idempotency_key_reused`. + * It describes only that attempt: the first may still have queued the email. + */ + public function getLaterError(): ?EmailError + { + return $this->laterError; + } +} diff --git a/lib/EmailBatchError.php b/lib/EmailBatchError.php new file mode 100644 index 0000000..9cc561e --- /dev/null +++ b/lib/EmailBatchError.php @@ -0,0 +1,54 @@ + $results + * @param list $warnings + */ + public function __construct(EmailError $error, private array $results, private array $warnings = []) + { + parent::__construct( + $error->getErrorCode(), + $error->getMessage(), + $error->getStatusCode(), + why: $error->getWhy(), + fix: $error->getFix(), + docsUrl: $error->getDocsUrl(), + field: $error->getField(), + retryAfterMs: $error->getRetryAfterMs(), + previous: $error, + messageId: $error->getMessageId() + ); + } + + /** + * One result per recipient, in the order of `recipients`. + * + * @return list + */ + public function getResults(): array + { + return $this->results; + } + + /** + * The warnings PostHog returned about the requests that went out, each once. + * + * @return list + */ + public function getWarnings(): array + { + return $this->warnings; + } +} diff --git a/lib/EmailError.php b/lib/EmailError.php index 730636f..d42a2b2 100644 --- a/lib/EmailError.php +++ b/lib/EmailError.php @@ -79,7 +79,7 @@ public function getErrorName(): string /** * PostHog's error code, such as `quota_limited`, or an SDK code such as `missing_secret_key`, * `missing_app_host`, `client_disabled`, `client_closed`, `network_error`, `api_error`, `attachment_upload_failed`, - * `scheduling_requires_cloud`, `schedule_not_confirmed` or an `invalid_*` argument code. + * `scheduling_requires_cloud`, `schedule_not_confirmed`, `not_attempted` or an `invalid_*` argument code. */ public function getErrorCode(): string { @@ -160,10 +160,11 @@ private static function nameFor(?int $status, string $code): string return 'validation_error'; } if ($status === null) { - if ($code === 'network_error') { - return 'service_unavailable'; - } - return str_starts_with($code, 'invalid_') ? 'validation_error' : 'application_error'; + return match (true) { + in_array($code, ['network_error', 'delivery_unavailable'], true) => 'service_unavailable', + $code === 'content_too_large', str_starts_with($code, 'invalid_') => 'validation_error', + default => 'application_error', + }; } return match ($status) { diff --git a/lib/Emails.php b/lib/Emails.php index 3caed5f..b386275 100644 --- a/lib/Emails.php +++ b/lib/Emails.php @@ -8,6 +8,9 @@ use DateTimeZone; use InvalidArgumentException; use JsonException; +use PostHog\Internal\EmailBatch; +use PostHog\Internal\EmailRecipient; +use PostHog\Internal\EmailReplies; use Symfony\Component\Clock\Clock; use Symfony\Component\Clock\ClockInterface; use Symfony\Component\Clock\MonotonicClock; @@ -16,7 +19,7 @@ /** * Sends transactional email, from an email template made in PostHog or from content your code rendered, - * and reads the status of each email it sent. + * to one recipient with send() or to many with batch(), and reads the status of each email it sent. * * Get it from the client with `$client->emails()` or `PostHog::emails()`. The client needs a project * secret API key (`phs_...`) as `$secretKey`: sending needs the `transactional_email:write` scope, reading @@ -47,6 +50,8 @@ final class Emails private const SEND_PATH = '/api/messaging/send/email/'; private const UPLOADS_PATH = '/api/messaging/attachments/uploads/'; private const STATUS_PATH = '/api/messaging/emails/%s/'; + private const BATCH_PATH = '/api/messaging/send/email_batch/'; + private const STATUS_BY_KEY_PATH = '/api/messaging/emails/status/'; private const US_APP_HOST = 'https://us.posthog.com'; private const EU_APP_HOST = 'https://eu.posthog.com'; private const CLOUD_APP_HOSTS = [ @@ -57,12 +62,21 @@ final class Emails 'eu.posthog.com' => self::EU_APP_HOST, ]; private const MAX_RETRY_DELAY_MS = 30000; + private const BATCH_REQUEST_TIMEOUT_MS = 45000; + private const LOST_ANSWER_CODES = ['network_error', 'response_too_large']; + private const FIELDS_A_BATCH_REFUSES = [ + 'to' => 'Give each address as to in recipients.', + 'distinct_id' => "Give each recipient's distinct_id in recipients.", + 'idempotency_key' => "Give each recipient's idempotency_key in recipients.", + 'scheduled_at' => 'Send each email with emails()->send(), which takes scheduled_at.', + 'cc' => 'Send each email with emails()->send(), which takes cc.', + 'bcc' => 'Send each email with emails()->send(), which takes bcc.', + 'attachments' => 'Send each email with emails()->send(), which takes attachments.', + ]; private const SEND_NOW_LEEWAY_SECONDS = 60; private const MAX_RESPONSE_BYTES = 1_048_576; - private const MAX_RETRY_AFTER_SECONDS = 31_536_000; private const NO_EXPECT_100_CONTINUE = 'Expect:'; private const UUID_PATTERN = '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iD'; - private const IDEMPOTENCY_KEY_PATTERN = '/^[\x21-\x7e]{1,255}$/D'; private const TEMPLATE_KEY_PATTERN = '/^[a-zA-Z0-9_-]{1,400}$/D'; private const HEADER_TOKEN_PATTERN = '/^[\x21-\x7e]+$/D'; private const TIMESTAMP_PATTERN = '/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:?\d{2})$/D'; @@ -329,12 +343,20 @@ function () use ($appHost, $headers, $body, $scheduledAt): SendEmailResult { return self::parseSendReply($scheduledAt, ...$reply); } ); - foreach ($result->getWarnings() as $warning) { + self::logWarnings($result->getWarnings()); + + return $result; + } + + /** + * @param list $warnings + */ + private static function logWarnings(array $warnings): void + { + foreach ($warnings as $warning) { $line = $warning->getCode() . ': ' . $warning->getMessage(); error_log('[PostHog][Emails] Email warning ' . self::onOneLogLine($line)); } - - return $result; } /** @@ -369,6 +391,111 @@ public function get(string $messageId): EmailStatus }); } + /** + * Queue the same email for many recipients, one email each, from a template made in PostHog or from content + * your code rendered. + * + * Pass one form, as send() takes it: + * + * - A template made transactional in PostHog: `template_id` and optional `template_data`, shared by every + * recipient. A recipient's own `template_data` is merged over it: a top-level key set for the recipient + * replaces the same key of the batch. + * - Content your code rendered, the same for every recipient: `template_key`, `subject`, and `html`, `text` + * or both, with optional `from`, `reply_to`, `sensitive`, `tracking` and `capture_engagement`. A recipient + * can't carry `template_data`: send personalized content with a `template_id` batch, or with send(). + * + * A batch takes no `cc`, `bcc`, `attachments` or `scheduled_at`, and no `to`, `distinct_id` or + * `idempotency_key` of its own: each throws `invalid_form` before any request. + * + * `recipients` is a list of 1 or more recipients, each an array with `to` and optional `distinct_id`, + * `idempotency_key` and `template_data`. A null value counts as left out. The client sends the recipients in + * requests of at most 100 recipients and 4 MiB of JSON, one request after another, and waits 45 seconds for + * each answer, or `email_request_timeout_ms` when that is longer. `max_retries` overrides the client's + * retries for each request. + * + * Each recipient's `idempotency_key` is 1 to 255 visible ASCII characters, a different one for each recipient + * of the call, and every retry reuses it, so a retry never queues an email twice. 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: after a lost answer, the client reads the email by its key, and an earlier email with + * that key reads as this one, `queued`. + * + * Check each result's getStatus(): + * + * - `queued`: PostHog accepted the email. + * - `failed`: PostHog refused it, and getError() says why, such as a suppressed address. + * - `unconfirmed`: the client can't tell whether PostHog accepted it, such as after a lost answer. Send it + * again with the same key within 24 hours, so it goes out once. + * - `not_attempted`: an earlier request of the batch failed, so the client sent nothing for it. + * + * A request that fails as a whole, such as a rate limit past its retries, stops the batch and throws + * EmailBatchError, whose getResults() holds every recipient. After a lost answer, the client reads each email + * it may have queued by its key, and reports the ones PostHog has as `queued`. The code `batch_unavailable` + * (409) means the project can't send batches yet, and `not_found` (404) that the template doesn't exist or + * batch sends are off for the project: send each email the batch didn't queue with send() and its recipient's + * `idempotency_key`. + * + * ```php + * $result = $client->emails()->batch([ + * 'template_id' => '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b', + * 'recipients' => [ + * ['to' => 'ada@example.com', 'template_data' => ['name' => 'Ada'], 'idempotency_key' => 'digest:ada'], + * ['to' => 'alan@example.com', 'template_data' => ['name' => 'Alan'], 'idempotency_key' => 'digest:alan'], + * ], + * ]); + * foreach ($result->getResults() as $email) { + * if ($email->getStatus() !== 'queued') { + * echo $email->getTo(), ': ', $email->getStatus(), ' ', $email->getError()?->getMessage(), PHP_EOL; + * } + * } + * ``` + * + * @param array{ + * recipients: list|null + * }>, + * max_retries?: int|null, + * template_id?: string, + * template_data?: array|null, + * template_key?: string, + * subject?: string, + * html?: string|null, + * text?: string|null, + * from?: string|null, + * reply_to?: string|list|null, + * sensitive?: bool|null, + * tracking?: bool|array{opens?: bool|null, clicks?: bool|null, engagement?: bool|null}|null, + * capture_engagement?: bool|null + * } $batch + * @return SendBatchResult A result per recipient, in the order of `recipients`. + * @throws EmailBatchError A request failed as a whole, so the batch stopped. getResults() holds every + * recipient, those not sent as `not_attempted`. The code `client_closed` means the client shut down during + * the batch. + * @throws EmailError The client sent nothing: an argument check failed, with the name `validation_error` and + * an `invalid_*` code, such as two recipients with the same `idempotency_key`, or the client can't send, + * such as when it is disabled. + */ + public function batch(array $batch): SendBatchResult + { + [$shared, $isTemplateForm, $maxRetries] = $this->prepareBatch($batch); + $run = EmailBatch::prepare($shared, $batch['recipients'] ?? null, $isTemplateForm); + [$appHost, $secretKey] = $this->connect(self::SEND_NOT_DONE, self::SEND_KEY_NEEDED); + try { + $this->sendBatch($run, $appHost, $secretKey, $maxRetries); + } catch (EmailBatchError $failure) { + self::logWarnings($failure->getWarnings()); + throw $failure; + } + $result = $run->result(); + self::logWarnings($result->getWarnings()); + + return $result; + } + /** * @return array{string, string, int, array, DateTimeImmutable|null} The body, the * idempotency key, the retries, the files to upload by SHA-256, and the time the email waits for. @@ -376,14 +503,7 @@ public function get(string $messageId): EmailStatus private function prepareSend(array $email): array { $email = array_filter($email, static fn($value): bool => $value !== null); - $to = $email['to'] ?? null; - if (!is_string($to) || trim($to) === '') { - throw self::invalid('invalid_recipient', 'to must be one email address as a nonempty string.', 'to'); - } - $distinctId = $email['distinct_id'] ?? null; - if ($distinctId !== null && (!is_string($distinctId) || $distinctId === '')) { - throw self::invalid('invalid_distinct_id', 'distinct_id must be a nonempty string.', 'distinct_id'); - } + [$to, $distinctId, $idempotencyKey] = EmailRecipient::check($email); $hasTemplateId = array_key_exists('template_id', $email); if ($hasTemplateId === array_key_exists('template_key', $email)) { throw new EmailError( @@ -392,21 +512,7 @@ private function prepareSend(array $email): array ); } [$payload, $files] = $hasTemplateId ? [self::templateContent($email), []] : self::codeContent($email); - $idempotencyKey = $email['idempotency_key'] ?? null; - if ( - $idempotencyKey !== null - && (!is_string($idempotencyKey) || preg_match(self::IDEMPOTENCY_KEY_PATTERN, $idempotencyKey) !== 1) - ) { - throw self::invalid( - 'invalid_idempotency_key', - 'idempotency_key must be 1 to 255 visible ASCII characters without spaces.', - 'idempotency_key' - ); - } - $maxRetries = $email['max_retries'] ?? $this->maxRetries; - if (!is_int($maxRetries) || $maxRetries < 0) { - throw self::invalid('invalid_max_retries', 'max_retries must be a nonnegative integer.', 'max_retries'); - } + $maxRetries = $this->maxRetries($email); $scheduledAt = array_key_exists('scheduled_at', $email) ? self::scheduledAt($email['scheduled_at']) : null; $payload['to'] = $to; if ($distinctId !== null) { @@ -428,6 +534,48 @@ private function prepareSend(array $email): array return [$body, $idempotencyKey ?? Uuid::v4(), $maxRetries, $files, $scheduledAt]; } + /** + * @return array{array, bool, int} The email every recipient gets, whether it is a template + * made in PostHog, and the retries of each request. + */ + private function prepareBatch(array $batch): array + { + $batch = array_filter($batch, static fn($value): bool => $value !== null); + foreach (self::FIELDS_A_BATCH_REFUSES as $field => $fix) { + if (array_key_exists($field, $batch)) { + throw new EmailError( + 'invalid_form', + "A batch doesn't take $field, so no email was sent.", + fix: $fix, + field: $field + ); + } + } + $isTemplateForm = array_key_exists('template_id', $batch); + if ($isTemplateForm === array_key_exists('template_key', $batch)) { + throw new EmailError( + 'invalid_form', + 'Send a batch with either template_id, or template_key with subject and html or text, so no email ' + . 'was sent.' + ); + } + $maxRetries = $this->maxRetries($batch); + unset($batch['recipients']); + $shared = $isTemplateForm ? self::templateContent($batch, 'batch') : self::codeContent($batch, 'batch')[0]; + + return [$shared, $isTemplateForm, $maxRetries]; + } + + private function maxRetries(array $call): int + { + $maxRetries = $call['max_retries'] ?? $this->maxRetries; + if (!is_int($maxRetries) || $maxRetries < 0) { + throw self::invalid('invalid_max_retries', 'max_retries must be a nonnegative integer.', 'max_retries'); + } + + return $maxRetries; + } + private static function scheduledAt(mixed $value): DateTimeImmutable { if ($value instanceof DateTimeInterface) { @@ -488,7 +636,7 @@ private static function roundedUpToTheMillisecond(DateTimeImmutable $time): Date /** * @return array */ - private static function templateContent(array $email): array + private static function templateContent(array $email, string $call = 'send'): array { $templateId = $email['template_id']; if (!is_string($templateId) || preg_match(self::UUID_PATTERN, $templateId) !== 1) { @@ -502,7 +650,7 @@ private static function templateContent(array $email): array 'template_data' ); } - self::refuseFieldsOutside($email, true); + self::refuseFieldsOutside($email, true, $call); return [ 'template_id' => strtolower($templateId), @@ -513,7 +661,7 @@ private static function templateContent(array $email): array /** * @return array{array, array} */ - private static function codeContent(array $email): array + private static function codeContent(array $email, string $call = 'send'): array { $templateKey = $email['template_key']; if (!is_string($templateKey) || preg_match(self::TEMPLATE_KEY_PATTERN, $templateKey) !== 1) { @@ -523,10 +671,10 @@ private static function codeContent(array $email): array 'template_key' ); } - self::refuseFieldsOutside($email, false); + self::refuseFieldsOutside($email, false, $call); $subject = $email['subject'] ?? null; if (!is_string($subject) || $subject === '') { - throw self::invalid('invalid_form', 'A send with template_key needs a nonempty subject.', 'subject'); + throw self::invalid('invalid_form', "A $call with template_key needs a nonempty subject.", 'subject'); } $content = ['template_key' => $templateKey, 'subject' => $subject]; foreach (['html', 'text'] as $field) { @@ -541,7 +689,7 @@ private static function codeContent(array $email): array if (($content['html'] ?? '') === '' && ($content['text'] ?? '') === '') { throw self::invalid( 'invalid_form', - 'A send with template_key needs a nonempty html, text or both.', + "A $call with template_key needs a nonempty html, text or both.", array_key_exists('html', $content) || !array_key_exists('text', $content) ? 'html' : 'text' ); } @@ -753,7 +901,7 @@ private static function invalidAttachment(string $message, string $field): Email return new EmailError('invalid_attachment', $message . ' No email was sent.', field: $field); } - private static function refuseFieldsOutside(array $email, bool $isTemplateForm): void + private static function refuseFieldsOutside(array $email, bool $isTemplateForm, string $call): void { $formFields = array_merge(self::SHARED_FIELDS, $isTemplateForm ? self::TEMPLATE_FIELDS : self::CODE_FIELDS); $otherFields = $isTemplateForm ? self::CODE_FIELDS : self::TEMPLATE_FIELDS; @@ -763,7 +911,7 @@ private static function refuseFieldsOutside(array $email, bool $isTemplateForm): } $field = (string) $field; $formName = $isTemplateForm ? 'template_id' : 'template_key'; - $message = "A send with $formName doesn't take $field, so no email was sent."; + $message = "A $call with $formName doesn't take $field, so no email was sent."; if (!in_array($field, $otherFields, true)) { throw new EmailError('invalid_form', $message, field: $field, fix: "Remove $field and send again."); } @@ -870,7 +1018,7 @@ private function put(string $url, array $headers, array $file): void why: 'PostHog sends an email with files only after every file reached its file storage.', fix: 'Send the email again. The client asks for a new upload URL on every send.', field: $file['field'], - retryAfterMs: self::retryAfterMs($answerHeaders) + retryAfterMs: EmailReplies::retryAfterMs($answerHeaders) ); } @@ -886,15 +1034,15 @@ private static function parseUploadReply( string $body, array $headers ): array { - $fields = self::replyFields($body); + $fields = EmailReplies::fields($body); if ($status === 404) { - $fields['code'] = self::text($fields['code'] ?? null) ?? 'not_found'; + $fields['code'] = EmailReplies::text($fields['code'] ?? null) ?? 'not_found'; $fields['attr'] = 'attachments'; - throw self::replyError($fields, $status, $headers); + throw EmailReplies::error($fields, $status, $headers); } if ($status < 200 || $status >= 300) { - $fields['attr'] = self::attachmentField(self::text($fields['attr'] ?? null), $files); - throw self::replyError($fields, $status, $headers); + $fields['attr'] = self::attachmentField(EmailReplies::text($fields['attr'] ?? null), $files); + throw EmailReplies::error($fields, $status, $headers); } $slots = []; foreach (is_array($fields['files'] ?? null) ? $fields['files'] : [] as $slot) { @@ -977,6 +1125,62 @@ private static function attachmentField(?string $uploadField, array $files): ?st return $index === null ? 'attachments' : array_values($files)[(int) $index]['field'] ?? 'attachments'; } + private function sendBatch(EmailBatch $run, string $appHost, string $secretKey, int $maxRetries): void + { + $headers = $this->headers($secretKey, ['Content-Type: application/json']); + $timeoutMs = max($this->requestTimeoutMs, self::BATCH_REQUEST_TIMEOUT_MS); + $closedBeforeARetry = new EmailError( + 'client_closed', + "The PostHog client is shut down, so it didn't retry this request of the batch." + ); + for ($position = 0; $position < $run->requestCount(); $position++) { + if ($position > 0 && ($this->isClosed)()) { + throw $run->failure($run->closedAt($position)); + } + $url = $appHost . self::BATCH_PATH; + $attemptOnce = function () use ($run, $position, $url, $headers, $timeoutMs): void { + try { + $reply = $this->request('POST', $url, $headers, $run->requestBody($position), $timeoutMs); + } catch (EmailError $error) { + if (in_array($error->getErrorCode(), self::LOST_ANSWER_CODES, true)) { + $run->lost($position); + } + throw $error; + } + $run->answer($position, ...$reply); + }; + try { + $this->withRetries($maxRetries, $attemptOnce, $closedBeforeARetry); + } catch (EmailError $error) { + $run->stop($position, $error); + $this->readLost($run, $appHost, $secretKey); + throw $run->failure($error); + } + } + } + + private function readLost(EmailBatch $run, string $appHost, string $secretKey): void + { + $headers = $this->headers($secretKey, []); + foreach ($run->keysToRead() as $index => $idempotencyKey) { + if (($this->isClosed)()) { + return; + } + $query = http_build_query(['idempotency_key' => $idempotencyKey], '', '&', PHP_QUERY_RFC3986); + try { + $status = self::parseStatusReply( + ...$this->request('GET', $appHost . self::STATUS_BY_KEY_PATH . '?' . $query, $headers, null) + ); + } catch (EmailError $error) { + if ($error->getStatusCode() === 404) { + continue; + } + return; + } + $run->accepted($index, $status->getId()); + } + } + /** * @return array{string, string} */ @@ -1062,9 +1266,11 @@ private function headers(string $secretKey, array $extra): array /** * @template T * @param Closure(): T $attemptOnce + * @param EmailError|null $closedBeforeARetry What to throw when the client shuts down before a retry, + * instead of the last attempt's error. * @return T */ - private function withRetries(int $maxRetries, Closure $attemptOnce): mixed + private function withRetries(int $maxRetries, Closure $attemptOnce, ?EmailError $closedBeforeARetry = null): mixed { for ($attempt = 0;; $attempt++) { try { @@ -1074,7 +1280,7 @@ private function withRetries(int $maxRetries, Closure $attemptOnce): mixed if ($delayMs === null) { throw $error; } - $this->waitToRetry($delayMs, $error); + $this->waitToRetry($delayMs, $closedBeforeARetry ?? $error); } } } @@ -1160,9 +1366,11 @@ private static function retryDelayMs(EmailError $error, int $attempt, int $maxRe * @param list $headers * @return array{int, string, list} */ - private function request(string $method, string $url, array $headers, ?string $body): array + private function request(string $method, string $url, array $headers, ?string $body, ?int $timeoutMs = null): array { - return ($this->transport)($method, $url, $headers, $body, $this->requestTimeoutMs, $this->requestTimeoutMs); + $timeoutMs ??= $this->requestTimeoutMs; + + return ($this->transport)($method, $url, $headers, $body, $timeoutMs, $this->requestTimeoutMs); } /** @@ -1237,25 +1445,15 @@ private static function parseSendReply( string $body, array $headers ): SendEmailResult { - $fields = self::replyFields($body); + $fields = EmailReplies::fields($body); if ($status < 200 || $status >= 300) { - throw self::replyError($fields, $status, $headers); + throw EmailReplies::error($fields, $status, $headers); } - $id = self::text($fields['message_id'] ?? null); + $id = EmailReplies::text($fields['message_id'] ?? null); if ($id === null) { throw new EmailError('api_error', 'PostHog answered without a message ID.', $status); } - $warnings = []; - foreach (is_array($fields['warnings'] ?? null) ? $fields['warnings'] : [] as $warning) { - if (is_array($warning)) { - $warnings[] = new EmailWarning( - self::text($warning['code'] ?? null) ?? 'warning', - self::text($warning['detail'] ?? null) ?? self::text($warning['message'] ?? null) ?? '', - self::text($warning['fix'] ?? null) - ); - } - } - + $warnings = EmailReplies::warnings($fields); $replayed = ($fields['replayed'] ?? false) === true; if ($scheduledAt === null || self::sendsNow($fields, $scheduledAt)) { return new SendEmailResult($id, $replayed, $warnings); @@ -1322,56 +1520,26 @@ private static function scheduleNotConfirmed(string $messageId, int $status): Em */ private static function parseStatusReply(int $status, string $body, array $headers): EmailStatus { - $fields = self::replyFields($body); + $fields = EmailReplies::fields($body); if ($status < 200 || $status >= 300) { - throw self::replyError($fields, $status, $headers); + throw EmailReplies::error($fields, $status, $headers); } - $id = self::text($fields['id'] ?? null); - $deliveryStatus = self::text($fields['status'] ?? null); + $id = EmailReplies::text($fields['id'] ?? null); + $deliveryStatus = EmailReplies::text($fields['status'] ?? null); $createdAt = self::timestamp($fields['created_at'] ?? null); $statusAt = self::timestamp($fields['status_at'] ?? null); if ($id === null || $deliveryStatus === null || $createdAt === null || $statusAt === null) { throw new EmailError('api_error', 'PostHog answered without an email status.', $status); } - return new EmailStatus($id, $deliveryStatus, $createdAt, $statusAt, self::text($fields['reason'] ?? null)); - } - - /** - * @param array $fields - * @param list $headers - */ - private static function replyError(array $fields, int $status, array $headers): EmailError - { - return new EmailError( - self::text($fields['code'] ?? null) ?? 'api_error', - self::text($fields['detail'] ?? null) ?? "PostHog answered HTTP $status.", - $status, - why: self::text($fields['why'] ?? null), - fix: self::text($fields['fix'] ?? null), - docsUrl: self::text($fields['docs_url'] ?? null), - field: self::text($fields['attr'] ?? null), - retryAfterMs: self::retryAfterMs($headers) - ); - } + $reason = EmailReplies::text($fields['reason'] ?? null); - /** - * @return array - */ - private static function replyFields(string $body): array - { - $payload = json_decode($body, true); - return is_array($payload) && !array_is_list($payload) ? $payload : []; - } - - private static function text(mixed $value): ?string - { - return is_string($value) && $value !== '' ? $value : null; + return new EmailStatus($id, $deliveryStatus, $createdAt, $statusAt, $reason); } private static function timestamp(mixed $value): ?DateTimeImmutable { - $text = self::text($value); + $text = EmailReplies::text($value); if ($text === null || preg_match(self::TIMESTAMP_PATTERN, $text) !== 1) { return null; } @@ -1382,43 +1550,6 @@ private static function timestamp(mixed $value): ?DateTimeImmutable } } - /** - * @param list $headers - */ - private static function retryAfterMs(array $headers): ?int - { - $value = null; - foreach ($headers as $header) { - if (stripos($header, 'retry-after:') === 0) { - $value = trim(substr($header, strlen('retry-after:'))); - } - } - if ($value === null || $value === '') { - return null; - } - if (is_numeric($value)) { - $seconds = (float) $value; - } else { - $date = self::httpDateInUtc($value); - if ($date === null) { - return null; - } - $seconds = self::epochSecondsAsFloat($date) - self::epochSecondsAsFloat(Clock::get()->now()); - } - - return (int) (min(max(0.0, $seconds), self::longestRetryAfterSecondsAnIntHoldsInMs()) * 1000); - } - - private static function httpDateInUtc(string $value): ?DateTimeImmutable - { - return DateTimeImmutable::createFromFormat(DATE_RFC7231, $value, new DateTimeZone('UTC')) ?: null; - } - - private static function longestRetryAfterSecondsAnIntHoldsInMs(): int - { - return min(self::MAX_RETRY_AFTER_SECONDS, intdiv(PHP_INT_MAX, 1000)); - } - private static function resolveAppHost(string $host, ?string $appHost): ?string { $appHost = StringNormalizer::normalizeOptional($appHost); diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php new file mode 100644 index 0000000..9f879ca --- /dev/null +++ b/lib/Internal/EmailBatch.php @@ -0,0 +1,479 @@ +send() and its recipient's " + . 'idempotency_key.'; + + /** @var list}> */ + private array $requests = []; + /** @var array */ + private array $results = []; + /** @var array */ + private array $maybeQueued = []; + /** @var list */ + private array $warnings = []; + + /** + * @param list $members + */ + private function __construct(private array $members, string $emptyBody) + { + $this->split($emptyBody); + } + + /** + * Checks every recipient before any request, and gives each the idempotency key its every attempt carries. + * + * @param array $shared The email every recipient gets, as the request carries it. + */ + public static function prepare(array $shared, mixed $recipients, bool $isTemplateForm): self + { + if (!is_array($recipients) || $recipients === [] || !array_is_list($recipients)) { + throw new EmailError( + 'invalid_recipients', + "recipients must be a nonempty list of recipients, such as [['to' => 'user@example.com']], so no " + . 'email was sent.', + field: 'recipients' + ); + } + $members = []; + $firstWithKey = []; + foreach ($recipients as $index => $recipient) { + $member = self::member($index, $recipient, $isTemplateForm); + $first = $firstWithKey[$member['key']] ??= $index; + if ($first !== $index) { + throw new EmailError( + 'invalid_idempotency_key', + "recipients[$index] has the same idempotency_key as recipients[$first], so no email was sent.", + why: 'PostHog sends one email per key, so the second recipient would get no email.', + fix: 'Give each recipient its own key.', + field: "recipients__{$index}__idempotency_key" + ); + } + $members[] = $member; + } + + return new self($members, self::encode([...$shared, 'recipients' => []], 'The email')); + } + + /** + * @return array{to: string, key: string, wire: string} + */ + private static function member(int $index, mixed $recipient, bool $isTemplateForm): array + { + if (!is_array($recipient) || ($recipient !== [] && array_is_list($recipient))) { + throw new EmailError( + 'invalid_recipient', + "recipients[$index] must be an array with to, such as ['to' => 'user@example.com'], so no email " + . 'was sent.', + field: "recipients__$index" + ); + } + $recipient = array_filter($recipient, static fn($value): bool => $value !== null); + foreach (array_keys($recipient) as $name) { + if (!in_array($name, self::RECIPIENT_FIELDS, true)) { + throw new EmailError( + 'invalid_form', + "recipients[$index] takes only to, distinct_id, idempotency_key and template_data, not $name, so " + . 'no email was sent.', + fix: 'Set the rest on the batch, or send this email with emails()->send().', + field: "recipients__{$index}__$name" + ); + } + } + [$to, $distinctId, $key] = EmailRecipient::check($recipient, $index); + $wire = ['to' => $to, 'idempotency_key' => $key ?? Uuid::v4()]; + if ($distinctId !== null) { + $wire['distinct_id'] = $distinctId; + } + if (array_key_exists('template_data', $recipient)) { + $wire['message_data'] = self::templateData($index, $recipient['template_data'], $isTemplateForm); + } + + return ['to' => $to, 'key' => $wire['idempotency_key'], 'wire' => self::encode($wire, "recipients[$index]")]; + } + + private static function templateData(int $index, mixed $data, bool $isTemplateForm): array|object + { + $field = "recipients__{$index}__template_data"; + if (!$isTemplateForm) { + throw new EmailError( + 'invalid_form', + "recipients[$index] has template_data, but a batch with template_key sends the same content to every " + . 'recipient, so no email was sent.', + fix: 'Send personalized content with a template_id batch, or with emails()->send().', + field: $field + ); + } + if (!is_array($data) || ($data !== [] && array_is_list($data))) { + throw new EmailError( + 'invalid_template_data', + "recipients[$index]: template_data must be an array with a value per variable name.", + field: $field + ); + } + + return $data === [] ? (object) [] : $data; + } + + private static function encode(array $payload, string $what): string + { + try { + return json_encode($payload, self::JSON_FLAGS); + } catch (JsonException $exception) { + throw new EmailError( + 'invalid_form', + "$what could not be encoded as JSON, so no email was sent: " . $exception->getMessage() . '.', + previous: $exception + ); + } + } + + /** + * Splits the recipients into requests of at most 100 recipients and 4 MiB, in order. A recipient too large for + * any request fails here and joins no request. + */ + private function split(string $emptyBody): void + { + $indices = []; + $wires = []; + $bytes = strlen($emptyBody); + foreach ($this->members as $index => $member) { + $memberBytes = strlen($member['wire']); + if (strlen($emptyBody) + $memberBytes > self::MAX_REQUEST_BYTES) { + $this->set($index, 'failed', error: self::recipientTooLarge()); + continue; + } + $separatorBytes = $indices === [] ? 0 : 1; + $full = count($indices) === self::MAX_RECIPIENTS_PER_REQUEST; + if ($indices !== [] && ($full || $bytes + $separatorBytes + $memberBytes > self::MAX_REQUEST_BYTES)) { + $this->addRequest($emptyBody, $indices, $wires); + [$indices, $wires, $bytes, $separatorBytes] = [[], [], strlen($emptyBody), 0]; + } + $indices[] = $index; + $wires[] = $member['wire']; + $bytes += $separatorBytes + $memberBytes; + } + if ($indices !== []) { + $this->addRequest($emptyBody, $indices, $wires); + } + } + + /** + * @param list $indices + * @param list $wires + */ + private function addRequest(string $emptyBody, array $indices, array $wires): void + { + $withoutClosingBrackets = substr($emptyBody, 0, -strlen(']}')); + $this->requests[] = ['body' => $withoutClosingBrackets . implode(',', $wires) . ']}', 'indices' => $indices]; + } + + public function requestCount(): int + { + return count($this->requests); + } + + public function requestBody(int $position): string + { + return $this->requests[$position]['body']; + } + + /** + * An attempt of request `$position` got no answer the client can read, so it may have queued any of its + * recipients. + */ + public function lost(int $position): void + { + foreach ($this->requests[$position]['indices'] as $index) { + $this->maybeQueued[$index] = true; + $messageId = ($this->results[$index] ?? null)?->getMessageId(); + $this->set($index, 'unconfirmed', $messageId, error: self::unconfirmed($messageId)); + } + } + + /** + * Records PostHog's answer to request `$position`. Throws the request's error when PostHog refused the whole + * request or its answer can't be read. + * + * @param list $headers + */ + public function answer(int $position, int $status, string $body, array $headers): void + { + $indices = $this->requests[$position]['indices']; + $fields = EmailReplies::fields($body); + if ($status < 200 || $status >= 300) { + if ($status >= 500) { + $this->lost($position); + } + throw self::requestError($fields, $status, $headers, $indices); + } + $slots = $fields['results'] ?? null; + if (!is_array($slots) || !array_is_list($slots) || count($slots) !== count($indices)) { + $this->lost($position); + throw new EmailError( + 'api_error', + 'PostHog answered the batch without a result for each recipient.', + $status + ); + } + foreach ($indices as $slot => $index) { + $this->settle($index, is_array($slots[$slot]) ? $slots[$slot] : []); + } + foreach (EmailReplies::warnings($fields) as $warning) { + if (!in_array($warning, $this->warnings)) { + $this->warnings[] = $warning; + } + } + } + + /** + * @param array $slot + */ + private function settle(int $index, array $slot): void + { + $messageId = EmailReplies::text($slot['message_id'] ?? null); + $error = $slot['error'] ?? null; + if ($error === null && ($slot['status'] ?? null) === 'queued' && $messageId !== null) { + $this->set($index, 'queued', $messageId, ($slot['replayed'] ?? null) === true); + return; + } + $answer = self::slotError($error, $messageId); + if (isset($this->maybeQueued[$index])) { + $earlier = $this->results[$index]; + $messageId ??= $earlier->getMessageId(); + $this->set($index, 'unconfirmed', $messageId, error: $earlier->getError(), laterError: $answer); + } elseif (in_array($answer->getErrorCode(), self::UNCONFIRMED_CODES, true)) { + $this->maybeQueued[$index] = true; + $this->set($index, 'unconfirmed', $messageId, error: $answer); + } else { + $this->set($index, 'failed', $messageId, error: $answer); + } + } + + /** + * Request `$position` failed as a whole, so the batch stops there. + */ + public function stop(int $position, EmailError $error): void + { + $status = $error->getStatusCode(); + $later = $status !== null && $status < 500 ? $error : null; + foreach ($this->requests[$position]['indices'] as $index) { + if (!isset($this->maybeQueued[$index])) { + $this->set($index, 'failed', error: $error); + } elseif ($later !== null) { + $earlier = $this->results[$index]; + $this->set( + $index, + 'unconfirmed', + $earlier->getMessageId(), + error: $earlier->getError(), + laterError: $later + ); + } + } + $this->skipFrom($position + 1, new EmailError( + 'not_attempted', + 'An earlier request of the batch failed, so the client sent nothing for this recipient.' + )); + } + + /** + * The client shut down before request `$position` went out. + */ + public function closedAt(int $position): EmailError + { + $error = new EmailError( + 'client_closed', + "The PostHog client is shut down, so the rest of the batch wasn't sent." + ); + $this->skipFrom($position, $error); + + return $error; + } + + private function skipFrom(int $position, EmailError $error): void + { + foreach (array_slice($this->requests, $position) as $request) { + foreach ($request['indices'] as $index) { + $this->set($index, 'not_attempted', error: $error); + } + } + } + + /** + * @return array The idempotency key of each recipient a lost answer left without a message ID, + * by its position in `recipients`. + */ + public function keysToRead(): array + { + $keys = []; + foreach ($this->maybeQueued as $index => $_) { + if ($this->results[$index]->getMessageId() === null) { + $keys[$index] = $this->members[$index]['key']; + } + } + ksort($keys); + + return $keys; + } + + public function accepted(int $index, string $messageId): void + { + $this->set($index, 'queued', $messageId); + } + + public function result(): SendBatchResult + { + return new SendBatchResult($this->outcome(), $this->warnings); + } + + public function failure(EmailError $error): EmailBatchError + { + return new EmailBatchError($error, $this->outcome(), $this->warnings); + } + + /** + * @return list + */ + private function outcome(): array + { + $results = []; + foreach (array_keys($this->members) as $index) { + $results[] = $this->results[$index]; + } + + return $results; + } + + private function set( + int $index, + string $status, + ?string $messageId = null, + bool $replayed = false, + ?EmailError $error = null, + ?EmailError $laterError = null + ): void { + $member = $this->members[$index]; + $this->results[$index] = new BatchEmailResult( + $index, + $member['to'], + $member['key'], + $status, + $messageId, + $replayed, + $error, + $laterError + ); + } + + /** + * @param array $fields + * @param list $headers + * @param list $indices + */ + private static function requestError(array $fields, int $status, array $headers, array $indices): EmailError + { + $answered = array_filter($fields, static fn($value): bool => $value !== null); + if (is_string($answered['attr'] ?? null)) { + $answered['attr'] = self::recipientsField($answered['attr'], $indices); + } + if ($status === 404) { + $answered += [ + 'code' => 'not_found', + 'detail' => 'PostHog found no batch send for this request, so no email was sent.', + 'why' => "The template doesn't exist, or batch sends are off for this project or this PostHog version.", + 'fix' => 'Check template_id, or ' . self::SEND_SINGLY, + ]; + } + if (($answered['code'] ?? null) === 'batch_unavailable') { + $answered['fix'] = 'Until batch sends are on for the project, ' . self::SEND_SINGLY; + } + + return EmailReplies::error($answered, $status, $headers); + } + + /** + * PostHog names a recipient by its position in the request. The caller knows it by its position in + * `recipients`. + * + * @param list $indices + */ + private static function recipientsField(string $attr, array $indices): string + { + if (preg_match('/^recipients__([0-9]+)((?:__.*)?)$/sD', $attr, $match) !== 1) { + return $attr; + } + [, $position, $rest] = $match; + if (strlen($position) > strlen((string) count($indices)) || (int) $position >= count($indices)) { + return 'recipients'; + } + + return 'recipients__' . $indices[(int) $position] . $rest; + } + + private static function slotError(mixed $error, ?string $messageId): EmailError + { + if (!is_array($error)) { + return new EmailError( + 'api_error', + 'PostHog answered without a readable result for this email, so it may still go out.', + messageId: $messageId + ); + } + $code = EmailReplies::text($error['code'] ?? null) ?? 'api_error'; + $status = $error['status'] ?? null; + + return new EmailError( + $code, + EmailReplies::text($error['detail'] ?? null) ?? "PostHog didn't queue this email: $code.", + is_int($status) ? $status : null, + messageId: $messageId + ); + } + + private static function unconfirmed(?string $messageId): EmailError + { + return new EmailError( + 'delivery_unavailable', + "PostHog didn't confirm this email, so it may still go out. Send it again with the same idempotency_key " + . 'within 24 hours, so it goes out once.', + messageId: $messageId + ); + } + + private static function recipientTooLarge(): EmailError + { + return new EmailError( + 'content_too_large', + "This recipient's email is larger than one batch request takes, so it wasn't sent.", + fix: "Send this recipient's email with emails()->send().", + field: 'recipients' + ); + } +} diff --git a/lib/Internal/EmailRecipient.php b/lib/Internal/EmailRecipient.php new file mode 100644 index 0000000..7fe502b --- /dev/null +++ b/lib/Internal/EmailRecipient.php @@ -0,0 +1,56 @@ + $fields The recipient's fields, without nulls. + * @param int|null $index The recipient's position in a batch's `recipients`, or null for a single send. + * @return array{string, ?string, ?string} The address, the distinct ID and the idempotency key. + */ + public static function check(array $fields, ?int $index = null): array + { + $to = $fields['to'] ?? null; + if (!is_string($to) || trim($to) === '') { + $message = 'to must be one email address as a nonempty string.'; + throw self::invalid('invalid_recipient', $message, 'to', $index); + } + $distinctId = $fields['distinct_id'] ?? null; + if ($distinctId !== null && (!is_string($distinctId) || $distinctId === '')) { + throw self::invalid('invalid_distinct_id', 'distinct_id must be a nonempty string.', 'distinct_id', $index); + } + $idempotencyKey = $fields['idempotency_key'] ?? null; + if ( + $idempotencyKey !== null + && (!is_string($idempotencyKey) || preg_match(self::IDEMPOTENCY_KEY_PATTERN, $idempotencyKey) !== 1) + ) { + throw self::invalid( + 'invalid_idempotency_key', + 'idempotency_key must be 1 to 255 visible ASCII characters without spaces.', + 'idempotency_key', + $index + ); + } + + return [$to, $distinctId, $idempotencyKey]; + } + + private static function invalid(string $code, string $message, string $field, ?int $index): EmailError + { + if ($index === null) { + return new EmailError($code, $message, field: $field); + } + + return new EmailError($code, "recipients[$index]: $message", field: "recipients__{$index}__$field"); + } +} diff --git a/lib/Internal/EmailReplies.php b/lib/Internal/EmailReplies.php new file mode 100644 index 0000000..7fb7897 --- /dev/null +++ b/lib/Internal/EmailReplies.php @@ -0,0 +1,113 @@ + The answer's JSON object, or no fields when it isn't one. + */ + public static function fields(string $body): array + { + $payload = json_decode($body, true); + return is_array($payload) && !array_is_list($payload) ? $payload : []; + } + + public static function text(mixed $value): ?string + { + return is_string($value) && $value !== '' ? $value : null; + } + + /** + * @param array $fields + * @param list $headers + */ + public static function error(array $fields, int $status, array $headers): EmailError + { + return new EmailError( + self::text($fields['code'] ?? null) ?? 'api_error', + self::text($fields['detail'] ?? null) ?? "PostHog answered HTTP $status.", + $status, + why: self::text($fields['why'] ?? null), + fix: self::text($fields['fix'] ?? null), + docsUrl: self::text($fields['docs_url'] ?? null), + field: self::text($fields['attr'] ?? null), + retryAfterMs: self::retryAfterMs($headers) + ); + } + + /** + * @param array $fields + * @return list + */ + public static function warnings(array $fields): array + { + $warnings = []; + foreach (is_array($fields['warnings'] ?? null) ? $fields['warnings'] : [] as $warning) { + if (is_array($warning)) { + $warnings[] = new EmailWarning( + self::text($warning['code'] ?? null) ?? 'warning', + self::text($warning['detail'] ?? null) ?? self::text($warning['message'] ?? null) ?? '', + self::text($warning['fix'] ?? null) + ); + } + } + + return $warnings; + } + + /** + * @param list $headers + */ + public static function retryAfterMs(array $headers): ?int + { + $value = null; + foreach ($headers as $header) { + if (stripos($header, 'retry-after:') === 0) { + $value = trim(substr($header, strlen('retry-after:'))); + } + } + if ($value === null || $value === '') { + return null; + } + if (is_numeric($value)) { + $seconds = (float) $value; + } else { + $date = self::httpDateInUtc($value); + if ($date === null) { + return null; + } + $seconds = self::epochSecondsAsFloat($date) - self::epochSecondsAsFloat(Clock::get()->now()); + } + + return (int) (min(max(0.0, $seconds), self::longestRetryAfterSecondsAnIntHoldsInMs()) * 1000); + } + + private static function httpDateInUtc(string $value): ?DateTimeImmutable + { + return DateTimeImmutable::createFromFormat(DATE_RFC7231, $value, new DateTimeZone('UTC')) ?: null; + } + + private static function epochSecondsAsFloat(DateTimeImmutable $time): float + { + return (float) $time->format('U.u'); + } + + private static function longestRetryAfterSecondsAnIntHoldsInMs(): int + { + return min(self::MAX_RETRY_AFTER_SECONDS, intdiv(PHP_INT_MAX, 1000)); + } +} diff --git a/lib/SendBatchResult.php b/lib/SendBatchResult.php new file mode 100644 index 0000000..e9c3743 --- /dev/null +++ b/lib/SendBatchResult.php @@ -0,0 +1,38 @@ + $results + * @param list $warnings + */ + public function __construct(private array $results, private array $warnings = []) + { + } + + /** + * One result per recipient, in the order of `recipients`. + * + * @return list + */ + public function getResults(): array + { + return $this->results; + } + + /** + * The warnings PostHog returned about the batch, each once. + * + * @return list + */ + public function getWarnings(): array + { + return $this->warnings; + } +} diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php new file mode 100644 index 0000000..67bfbd2 --- /dev/null +++ b/test/EmailsBatchTest.php @@ -0,0 +1,860 @@ +send() and its recipient's " + . 'idempotency_key.'; + + private bool $closed = false; + + /** + * Answers each request with the next reply: an answer, an EmailError the transport throws, or a Closure + * of the request's URL, body and timeout that returns either. + * + * @param list $headers + * @return array{int, string, list} + */ + public function transport( + string $method, + string $url, + array $headers, + ?string $body, + int $timeoutMs, + int $connectTimeoutMs + ): array { + $at = Clock::get()->now(); + $this->requests[] = compact('method', 'url', 'headers', 'body', 'timeoutMs', 'at'); + if (self::headerIn($headers, 'Authorization') !== "Bearer {$this->secretKey}") { + return [401, '{"type":"authentication_error","code":"authentication_failed","detail":"Bad key."}', []]; + } + if ($this->replies === []) { + $this->fail("PostHog got a request the test has no answer for: $method $url"); + } + $reply = array_shift($this->replies); + if ($reply instanceof Closure) { + $reply = $reply($url, (string) $body, $timeoutMs); + } + if ($reply instanceof EmailError) { + throw $reply; + } + + return $reply; + } + + private function closedEmails(): Emails + { + return $this->emails(['isClosed' => fn(): bool => $this->closed]); + } + + private static function queued(string $messageId, bool $replayed = false): array + { + return ['message_id' => $messageId, 'status' => 'queued', 'replayed' => $replayed]; + } + + private static function refused(string $messageId, string $code, int $status = 422, bool $retryable = false): array + { + return [ + 'message_id' => $messageId, + 'error' => ['code' => $code, 'detail' => "Refused: $code.", 'status' => $status, 'retryable' => $retryable], + ]; + } + + /** @return array{int, string, list} */ + private static function ok(array ...$slots): array + { + return [200, json_encode(['results' => $slots]), []]; + } + + private static function allQueued(array $fields = []): Closure + { + return static function (string $url, string $body) use ($fields): array { + $slots = array_map( + static fn(array $recipient): array => self::queued('msg_' . $recipient['idempotency_key']), + json_decode($body, true)['recipients'] + ); + + return [200, json_encode(['results' => $slots, ...$fields]), []]; + }; + } + + /** @return array{int, string, list} */ + private static function wholeCall(int $status, ?string $code = null): array + { + $body = $code === null ? '' : json_encode(['type' => 'invalid_request', 'code' => $code, 'detail' => 'Nope.']); + + return [$status, $body, []]; + } + + /** @return array{int, string, list} */ + private static function statusFound(string $messageId): array + { + return [200, json_encode([ + 'id' => $messageId, + 'status' => 'sent', + 'created_at' => '2026-11-02T10:00:00Z', + 'status_at' => '2026-11-02T10:00:01Z', + ]), []]; + } + + /** A server that answers after this many seconds: a request with a shorter timeout gets no answer. */ + private static function slow(int $seconds, Closure $answer): Closure + { + return static function (string $url, string $body, int $timeoutMs) use ($seconds, $answer) { + if ($timeoutMs < $seconds * 1000) { + return self::networkError(); + } + + return $answer($url, $body); + }; + } + + private static function networkError(): EmailError + { + return new EmailError('network_error', 'The request to PostHog failed: Connection reset.'); + } + + /** @return list> */ + private static function recipients(int $count, array $extra = []): array + { + $recipients = []; + for ($index = 0; $index < $count; $index++) { + $recipients[] = ['to' => "user$index@example.com", 'idempotency_key' => "key-$index", ...$extra]; + } + + return $recipients; + } + + private function batch(array $recipients, array $overrides = [], ?Emails $emails = null): SendBatchResult + { + return ($emails ?? $this->emails())->batch( + ['recipients' => $recipients, 'template_id' => self::TEMPLATE_ID, ...$overrides] + ); + } + + private function batchError(array $recipients, array $overrides = [], ?Emails $emails = null): EmailBatchError + { + try { + $this->batch($recipients, $overrides, $emails); + } catch (EmailBatchError $error) { + return $error; + } + $this->fail('batch() did not throw EmailBatchError'); + } + + private function refusal(array $batch, ?Emails $emails = null): EmailError + { + try { + ($emails ?? $this->emails())->batch($batch); + } catch (EmailError $error) { + return $error; + } + $this->fail('batch() did not throw EmailError'); + } + + /** @return list> */ + private function batchBodies(): array + { + $bodies = []; + foreach ($this->requests as $index => $request) { + if ($request['url'] === self::BATCH_URL) { + $bodies[] = $this->body($index); + } + } + + return $bodies; + } + + /** @return list */ + private function recipientsPerRequest(): array + { + return array_map(static fn(array $body): int => count($body['recipients']), $this->batchBodies()); + } + + /** @return list the idempotency keys of the emails read by key, in order */ + private function readsByKey(): array + { + $keys = []; + foreach ($this->requests as $request) { + if (str_starts_with($request['url'], self::STATUS_BY_KEY_URL)) { + parse_str((string) parse_url($request['url'], PHP_URL_QUERY), $query); + $keys[] = $query['idempotency_key']; + } + } + + return $keys; + } + + /** @return list */ + private static function times(int $count, string $status): array + { + return array_fill(0, $count, $status); + } + + /** + * @param list $results + * @return list + */ + private static function statuses(array $results): array + { + return array_map(static fn(BatchEmailResult $result): string => $result->getStatus(), $results); + } + + public function testATemplateBatchPostsOneRequestWithAResultPerRecipient(): void + { + $this->reply(self::ok( + self::queued('m0'), + self::queued('m1', true), + self::refused('m2', 'recipient_suppressed') + )); + + $result = $this->batch([ + ['to' => 'a@example.com', 'idempotency_key' => 'welcome:a', 'distinct_id' => 'a'], + ['to' => 'b@example.com', 'template_data' => ['name' => 'Bea'], 'distinct_id' => null], + ['to' => 'c@example.com', 'idempotency_key' => 'welcome:c'], + ], ['template_data' => ['name' => 'friend', 'plan' => 'pro']]); + + $this->assertCount(1, $this->requests); + $this->assertSame(['POST', self::BATCH_URL], [$this->requests[0]['method'], $this->requests[0]['url']]); + $this->assertSame('Bearer phs_secret', $this->header('Authorization')); + $this->assertSame('application/json', $this->header('Content-Type')); + $this->assertNull($this->header('Idempotency-Key')); + $body = $this->body(); + $generated = $body['recipients'][1]['idempotency_key']; + $this->assertMatchesRegularExpression(self::UUID_V4, $generated); + $this->assertEquals([ + 'template_id' => self::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'], + ], + ], $body); + $results = $result->getResults(); + $this->assertSame([0, 1, 2], array_map(static fn($r): int => $r->getIndex(), $results)); + $this->assertSame( + ['a@example.com', 'b@example.com', 'c@example.com'], + array_map(static fn($r): string => $r->getTo(), $results) + ); + $this->assertSame( + ['welcome:a', $generated, 'welcome:c'], + array_map(static fn($r): string => $r->getIdempotencyKey(), $results) + ); + $this->assertSame( + [['queued', 'm0', false], ['queued', 'm1', true], ['failed', 'm2', false]], + array_map(static fn($r): array => [$r->getStatus(), $r->getMessageId(), $r->isReplayed()], $results) + ); + $this->assertNull($results[0]->getError()); + $error = $results[2]->getError(); + $this->assertSame( + ['recipient_suppressed', 422, 'm2', 'Refused: recipient_suppressed.', 'validation_error'], + [ + $error->getErrorCode(), + $error->getStatusCode(), + $error->getMessageId(), + $error->getMessage(), + $error->getErrorName(), + ] + ); + $this->assertNull($results[2]->getLaterError()); + $this->assertSame([], $result->getWarnings()); + } + + public function testATemplateBatchWithoutDataSendsAnEmptyObject(): void + { + $this->reply(self::allQueued()); + + $this->batch([['to' => 'a@example.com', 'idempotency_key' => 'k', 'template_data' => []]]); + + $this->assertSame( + '{"template_id":"' . self::TEMPLATE_ID . '","message_data":{},"recipients":' + . '[{"to":"a@example.com","idempotency_key":"k","message_data":{}}]}', + $this->requests[0]['body'] + ); + } + + public function testACodeBatchSendsTheSameContentToEveryRecipient(): void + { + $this->reply(self::allQueued()); + + $result = $this->emails()->batch([ + 'recipients' => self::recipients(2), + 'template_key' => 'launch-news', + 'subject' => 'We launched', + 'html' => '

Hi

', + 'from' => 'Acme ', + 'reply_to' => 'support@example.com', + 'tracking' => false, + 'sensitive' => null, + ]); + + $this->assertEquals([ + 'template_key' => 'launch-news', + 'subject' => 'We launched', + 'html' => '

Hi

', + 'from' => 'Acme ', + 'reply_to' => ['support@example.com'], + 'tracking' => false, + 'recipients' => [ + ['to' => 'user0@example.com', 'idempotency_key' => 'key-0'], + ['to' => 'user1@example.com', 'idempotency_key' => 'key-1'], + ], + ], $this->body()); + $this->assertSame(['queued', 'queued'], self::statuses($result->getResults())); + } + + public static function batchRefusals(): array + { + $code = ['template_key' => 'k', 'subject' => 's', 'html' => 'h']; + + return [ + 'scheduled_at' => [['scheduled_at' => '2026-12-01T09:00:00Z'], 'invalid_form', 'scheduled_at'], + 'cc' => [[...$code, 'cc' => 'x@example.com'], 'invalid_form', 'cc'], + 'bcc' => [[...$code, 'bcc' => 'x@example.com'], 'invalid_form', 'bcc'], + 'attachments' => [[...$code, 'attachments' => []], 'invalid_form', 'attachments'], + 'to on the batch' => [['to' => 'a@example.com'], 'invalid_form', 'to'], + 'idempotency_key on the batch' => [['idempotency_key' => 'k'], 'invalid_form', 'idempotency_key'], + 'unknown field' => [['colour' => 'blue'], 'invalid_form', 'colour'], + 'no recipients' => [['recipients' => []], 'invalid_recipients', 'recipients'], + 'recipients left out' => [['recipients' => null], 'invalid_recipients', 'recipients'], + 'recipients not a list' => [['recipients' => 'a@example.com'], 'invalid_recipients', 'recipients'], + 'recipient not an array' => [['recipients' => ['a@example.com']], 'invalid_recipient', 'recipients__0'], + 'recipient without to' => [ + ['recipients' => [['distinct_id' => 'a']]], + 'invalid_recipient', + 'recipients__0__to', + ], + 'recipient with a blank to' => [ + ['recipients' => [['to' => ' ']]], + 'invalid_recipient', + 'recipients__0__to', + ], + 'recipient with an unknown field' => [ + ['recipients' => [['to' => 'a@example.com', 'cc' => 'b@example.com']]], + 'invalid_form', + 'recipients__0__cc', + ], + 'recipient with an empty distinct_id' => [ + ['recipients' => [['to' => 'a@example.com', 'distinct_id' => '']]], + 'invalid_distinct_id', + 'recipients__0__distinct_id', + ], + 'recipient with a bad key' => [ + ['recipients' => [['to' => 'a@example.com', 'idempotency_key' => 'has space']]], + 'invalid_idempotency_key', + 'recipients__0__idempotency_key', + ], + 'recipient with a list as template_data' => [ + ['recipients' => [['to' => 'a@example.com', 'template_data' => [1]]]], + 'invalid_template_data', + 'recipients__0__template_data', + ], + 'code form recipient with template_data' => [ + [...$code, 'recipients' => [['to' => 'a@example.com', 'template_data' => ['a' => 1]]]], + 'invalid_form', + 'recipients__0__template_data', + ], + 'both forms' => [[...$code, 'template_id' => self::TEMPLATE_ID], 'invalid_form', null], + 'neither form' => [['template_id' => null], 'invalid_form', null], + 'bad template_id' => [['template_id' => 'welcome'], 'invalid_template_id', 'template_id'], + 'bad shared template_data' => [['template_data' => 'Ada'], 'invalid_template_data', 'template_data'], + 'code form without content' => [['template_key' => 'k', 'subject' => 's'], 'invalid_form', 'html'], + 'bad max_retries' => [['max_retries' => -1], 'invalid_max_retries', 'max_retries'], + ]; + } + + #[DataProvider('batchRefusals')] + public function testRefusesWhatABatchDoesNotTakeBeforeAnyRequest( + array $overrides, + string $code, + ?string $field + ): void { + $batch = ['recipients' => self::recipients(1), 'template_id' => self::TEMPLATE_ID, ...$overrides]; + if (array_key_exists('template_key', $overrides) && !array_key_exists('template_id', $overrides)) { + unset($batch['template_id']); + } + + $error = $this->refusal($batch); + + $this->assertNotInstanceOf(EmailBatchError::class, $error); + $this->assertSame([$code, $field], [$error->getErrorCode(), $error->getField()]); + $this->assertSame('validation_error', $error->getErrorName()); + $this->assertSame([], $this->requests); + } + + public function testACodeBatchWithoutContentSaysWhatABatchNeeds(): void + { + $error = $this->refusal(['template_key' => 'digest', 'subject' => 'Hi', 'recipients' => self::recipients(1)]); + + $this->assertSame('A batch with template_key needs a nonempty html, text or both.', $error->getMessage()); + } + + public function testNamesBothPositionsOfARepeatedIdempotencyKey(): void + { + $recipients = self::recipients(3); + $recipients[2]['idempotency_key'] = 'key-0'; + + $error = $this->refusal(['recipients' => $recipients, 'template_id' => self::TEMPLATE_ID]); + + $this->assertSame('invalid_idempotency_key', $error->getErrorCode()); + $this->assertSame('recipients__2__idempotency_key', $error->getField()); + $this->assertStringContainsString( + 'recipients[2] has the same idempotency_key as recipients[0]', + $error->getMessage() + ); + $this->assertSame([], $this->requests); + } + + public function testNamesThePositionOfABadRecipient(): void + { + $recipients = self::recipients(3); + $recipients[1]['to'] = ''; + + $error = $this->refusal(['recipients' => $recipients, 'template_id' => self::TEMPLATE_ID]); + + $this->assertSame('recipients__1__to', $error->getField()); + $this->assertStringStartsWith('recipients[1]: ', $error->getMessage()); + } + + public function testSplitsBy100RecipientsAndSendsTheRequestsInOrder(): void + { + $this->reply(self::allQueued(), self::allQueued(), self::allQueued()); + + $result = $this->batch(self::recipients(250)); + + $this->assertSame([100, 100, 50], $this->recipientsPerRequest()); + $results = $result->getResults(); + $this->assertSame(range(0, 249), array_map(static fn($r): int => $r->getIndex(), $results)); + $this->assertSame( + array_map(static fn(int $i): string => "msg_key-$i", range(0, 249)), + array_map(static fn($r): ?string => $r->getMessageId(), $results) + ); + $this->assertSame(self::times(250, 'queued'), self::statuses($results)); + } + + public function testSplitsByThe4MibBodyAndFailsOnlyARecipientTooLargeAlone(): void + { + $recipients = self::recipients(5, ['template_data' => ['note' => str_repeat('x', intdiv(self::FOUR_MIB, 3))]]); + $recipients[3]['template_data'] = ['note' => str_repeat('y', self::FOUR_MIB)]; + $this->reply(self::allQueued(), self::allQueued()); + + $result = $this->batch($recipients); + + foreach ($this->requests as $request) { + $this->assertLessThanOrEqual(self::FOUR_MIB, strlen($request['body'])); + } + $this->assertSame( + [['key-0', 'key-1'], ['key-2', 'key-4']], + array_map( + static fn(array $body): array => array_column($body['recipients'], 'idempotency_key'), + $this->batchBodies() + ) + ); + $results = $result->getResults(); + $this->assertSame(['queued', 'queued', 'queued', 'failed', 'queued'], self::statuses($results)); + $tooLarge = $results[3]; + $this->assertSame(['content_too_large', 'recipients', 'validation_error'], [ + $tooLarge->getError()->getErrorCode(), + $tooLarge->getError()->getField(), + $tooLarge->getError()->getErrorName(), + ]); + $this->assertSame([null, 'key-3'], [$tooLarge->getMessageId(), $tooLarge->getIdempotencyKey()]); + } + + public static function requestsAtTheLimit(): array + { + return [ + 'exactly 4 MiB' => [0, [3]], + 'one byte more' => [1, [2, 1]], + ]; + } + + #[DataProvider('requestsAtTheLimit')] + public function testARequestTakesRecipientsUpToExactly4Mib(int $bytesOver, array $recipientsPerRequest): void + { + $empty = ['template_id' => self::TEMPLATE_ID, 'message_data' => new stdClass(), 'recipients' => []]; + $base = strlen(json_encode($empty)); + $recipient = ['to' => 'a@example.com', 'idempotency_key' => 'k1', 'message_data' => ['n' => '']]; + $item = strlen(json_encode($recipient)); + $recipient = ['to' => 'a@example.com', 'idempotency_key' => 'k1', 'template_data' => ['n' => '']]; + $note = str_repeat('a', self::FOUR_MIB - $base - 3 * $item - 2 + $bytesOver); + $this->reply(...array_fill(0, count($recipientsPerRequest), self::allQueued())); + + $this->batch([ + [...$recipient, 'template_data' => ['n' => $note]], + [...$recipient, 'idempotency_key' => 'k2'], + [...$recipient, 'idempotency_key' => 'k3'], + ]); + + $this->assertSame($recipientsPerRequest, $this->recipientsPerRequest()); + } + + public function testABatchWaitsForASlowAnswerWhateverTheClientTimeout(): void + { + $this->reply(self::slow(40, self::allQueued())); + + $result = $this->batch(self::recipients(1), emails: $this->emails(['requestTimeoutMs' => 3000])); + + $this->assertSame(['queued'], self::statuses($result->getResults())); + } + + public function testALongerClientTimeoutAppliesToABatchToo(): void + { + $this->reply(self::slow(50, self::allQueued())); + + $result = $this->batch(self::recipients(1), emails: $this->emails(['requestTimeoutMs' => 60000])); + + $this->assertSame(['queued'], self::statuses($result->getResults())); + } + + public function testARetryAfterALostAnswerKeepsARefusedRecipientUnconfirmed(): void + { + $this->reply( + self::networkError(), + self::ok(self::queued('m0', true), self::refused('m1', 'idempotency_key_reused')) + ); + + $result = $this->batch(self::recipients(2)); + + $this->assertCount(2, $this->requests); + $this->assertSame($this->requests[0]['body'], $this->requests[1]['body']); + [$first, $second] = $result->getResults(); + $this->assertSame(['queued', 'm0', true], [$first->getStatus(), $first->getMessageId(), $first->isReplayed()]); + $this->assertSame(['unconfirmed', 'm1'], [$second->getStatus(), $second->getMessageId()]); + $this->assertSame('delivery_unavailable', $second->getError()->getErrorCode()); + $this->assertSame('service_unavailable', $second->getError()->getErrorName()); + $this->assertSame('idempotency_key_reused', $second->getLaterError()->getErrorCode()); + } + + public function testAnAnswerTooLargeToReadLeavesTheRequestUnconfirmed(): void + { + $this->reply( + new EmailError('response_too_large', 'PostHog answered with more than 1048576 bytes.'), + self::wholeCall(404, 'not_found') + ); + + $error = $this->batchError(self::recipients(1)); + + $this->assertSame('response_too_large', $error->getErrorCode()); + $this->assertSame(['unconfirmed'], self::statuses($error->getResults())); + $this->assertSame(['key-0'], $this->readsByKey()); + } + + public function testA503ThenARefusalAlsoKeepsTheRecipientUnconfirmed(): void + { + $this->reply(self::wholeCall(503, 'delivery_unavailable'), self::ok(self::refused('m0', 'sending_paused'))); + + [$result] = $this->batch(self::recipients(1))->getResults(); + + $this->assertSame('unconfirmed', $result->getStatus()); + $this->assertSame('sending_paused', $result->getLaterError()->getErrorCode()); + } + + public static function answersThatMayStillGoOut(): array + { + return [ + 'not confirmed by the pipeline' => [self::refused('m0', 'delivery_unavailable', 503, true)], + 'held by another request' => [self::refused('m0', 'idempotency_key_in_flight', 409, true)], + ]; + } + + #[DataProvider('answersThatMayStillGoOut')] + public function testARecipientPostHogMayStillSendIsUnconfirmed(array $answer): void + { + $this->reply(self::ok($answer)); + + [$result] = $this->batch(self::recipients(1))->getResults(); + + $this->assertSame(['unconfirmed', 'm0'], [$result->getStatus(), $result->getMessageId()]); + $this->assertSame($answer['error']['code'], $result->getError()->getErrorCode()); + $this->assertNull($result->getLaterError()); + } + + public function testAShutdownDuringABatchStopsItBeforeTheNextRequest(): void + { + $this->reply(function (string $url, string $body): array { + $this->closed = true; + + return self::allQueued()($url, $body); + }, self::allQueued()); + + $error = $this->batchError(self::recipients(150), emails: $this->closedEmails()); + + $this->assertSame('client_closed', $error->getErrorCode()); + $this->assertCount(1, $this->requests); + $this->assertSame( + [...self::times(100, 'queued'), ...self::times(50, 'not_attempted')], + self::statuses($error->getResults()) + ); + $this->assertSame('client_closed', $error->getResults()[100]->getError()->getErrorCode()); + } + + public function testAShutdownDuringARetryWaitSendsNoRetry(): void + { + $this->reply(function (): array { + $this->closed = true; + + return self::wholeCall(429); + }, self::allQueued()); + + $error = $this->batchError(self::recipients(150), emails: $this->closedEmails()); + + $this->assertSame('client_closed', $error->getErrorCode()); + $this->assertCount(1, $this->requests); + $this->assertSame( + [...self::times(100, 'failed'), ...self::times(50, 'not_attempted')], + self::statuses($error->getResults()) + ); + $this->assertSame('client_closed', $error->getResults()[0]->getError()->getErrorCode()); + } + + public function testAShutdownBeforeALostAnswerReadsNoEmailByItsKey(): void + { + $this->reply(function (): array { + $this->closed = true; + + return self::wholeCall(503, 'delivery_unavailable'); + }, self::statusFound('m0')); + + $error = $this->batchError(self::recipients(2), ['max_retries' => 0], $this->closedEmails()); + + $this->assertSame('delivery_unavailable', $error->getErrorCode()); + $this->assertCount(1, $this->requests); + $this->assertSame(['unconfirmed', 'unconfirmed'], self::statuses($error->getResults())); + } + + public function testARequestRefusedAsAWholeThrowsWithTheResultsSoFar(): void + { + $this->reply(self::allQueued(), self::wholeCall(429, 'quota_limited')); + + $error = $this->batchError(self::recipients(250)); + + $this->assertInstanceOf(EmailError::class, $error); + $this->assertSame( + ['quota_limited', 429, 'Nope.'], + [$error->getErrorCode(), $error->getStatusCode(), $error->getMessage()] + ); + $this->assertCount(2, $this->requests); + $results = $error->getResults(); + $this->assertSame( + [...self::times(100, 'queued'), ...self::times(100, 'failed'), ...self::times(50, 'not_attempted')], + self::statuses($results) + ); + $this->assertSame(['quota_limited', 'Nope.'], [ + $results[150]->getError()->getErrorCode(), + $results[150]->getError()->getMessage(), + ]); + $this->assertSame('not_attempted', $results[200]->getError()->getErrorCode()); + $this->assertSame('key-249', $results[249]->getIdempotencyKey()); + } + + public function testARefusalOfTheWholeRequestAfterALostAnswerKeepsItsRecipientsUnconfirmed(): void + { + $this->reply(self::networkError(), self::wholeCall(429, 'quota_limited'), self::wholeCall(404, 'not_found')); + + $error = $this->batchError(self::recipients(1)); + + [$result] = $error->getResults(); + $this->assertSame('unconfirmed', $result->getStatus()); + $this->assertSame('delivery_unavailable', $result->getError()->getErrorCode()); + $this->assertSame('quota_limited', $result->getLaterError()->getErrorCode()); + $this->assertSame(['key-0'], $this->readsByKey()); + } + + public function testALostAnswerAfterTheRetriesReadsEachEmailByItsKey(): void + { + $statusByKey = static function (string $url): array { + return str_ends_with($url, '=key-0') ? self::statusFound('m0') : self::wholeCall(404, 'not_found'); + }; + $this->reply(self::networkError(), self::networkError(), self::networkError(), $statusByKey, $statusByKey); + + $error = $this->batchError(self::recipients(2)); + + $this->assertSame('network_error', $error->getErrorCode()); + $this->assertSame(['key-0', 'key-1'], $this->readsByKey()); + $this->assertSame( + [['queued', 'm0'], ['unconfirmed', null]], + array_map(static fn($r): array => [$r->getStatus(), $r->getMessageId()], $error->getResults()) + ); + $this->assertSame('delivery_unavailable', $error->getResults()[1]->getError()->getErrorCode()); + } + + public function testAnEmailWithAMessageIdIsNotReadByItsKey(): void + { + $this->reply( + self::ok(self::refused('m0', 'delivery_unavailable', 503, true), ...array_fill(0, 99, self::queued('m'))), + self::networkError(), + ...array_fill(0, 50, self::wholeCall(404, 'not_found')) + ); + + $error = $this->batchError(self::recipients(150), ['max_retries' => 0]); + + $this->assertSame(array_map(static fn(int $i): string => "key-$i", range(100, 149)), $this->readsByKey()); + $first = $error->getResults()[0]; + $this->assertSame(['unconfirmed', 'm0'], [$first->getStatus(), $first->getMessageId()]); + } + + public function testReadingByKeyStopsWhenPostHogStaysUnreachable(): void + { + $unavailable = self::wholeCall(503, 'delivery_unavailable'); + $this->reply($unavailable, $unavailable, $unavailable, self::networkError()); + + $error = $this->batchError(self::recipients(3), ['max_retries' => 2]); + + $this->assertCount(4, $this->requests); + $this->assertSame(['unconfirmed', 'unconfirmed', 'unconfirmed'], self::statuses($error->getResults())); + } + + public function testAKeyWithReservedCharactersIsEncodedInTheStatusRead(): void + { + $this->reply(self::networkError(), self::wholeCall(404, 'not_found')); + + $this->batchError([['to' => 'a@example.com', 'idempotency_key' => 'order#1&x=2']], ['max_retries' => 0]); + + $this->assertSame(['order#1&x=2'], $this->readsByKey()); + } + + public function testBatchUnavailableIsNotRetriedAndSaysToSendEachEmailOnItsOwn(): void + { + $this->reply(self::wholeCall(409, 'batch_unavailable')); + + $error = $this->batchError(self::recipients(2)); + + $this->assertCount(1, $this->requests); + $this->assertSame('batch_unavailable', $error->getErrorCode()); + $this->assertSame('Until batch sends are on for the project, ' . self::SEND_SINGLY, $error->getFix()); + $this->assertSame(['failed', 'failed'], self::statuses($error->getResults())); + } + + public static function notFoundAnswers(): array + { + return [ + 'empty body' => ['', 'PostHog found no batch send for this request, so no email was sent.'], + "PostHog's answer" => ['{"type":"invalid_request","code":"not_found","detail":"Not found."}', 'Not found.'], + ]; + } + + #[DataProvider('notFoundAnswers')] + public function testA404SaysBatchSendsAreUnavailable(string $body, string $message): void + { + $this->reply([404, $body, []]); + + $error = $this->batchError(self::recipients(1)); + + $this->assertSame(['not_found', $message], [$error->getErrorCode(), $error->getMessage()]); + $this->assertStringContainsString('batch sends', strtolower((string) $error->getWhy())); + $this->assertSame('Check template_id, or ' . self::SEND_SINGLY, $error->getFix()); + } + + public function testAnAnswerWithoutAResultPerRecipientLeavesTheRequestUnconfirmed(): void + { + $notFound = self::wholeCall(404, 'not_found'); + $this->reply(self::ok(self::queued('m0')), $notFound, $notFound); + + $error = $this->batchError(self::recipients(2), ['max_retries' => 0]); + + $this->assertSame('api_error', $error->getErrorCode()); + $this->assertSame(['unconfirmed', 'unconfirmed'], self::statuses($error->getResults())); + $this->assertSame(['key-0', 'key-1'], $this->readsByKey()); + } + + public function testWarningsReachTheCallerOnce(): void + { + global $errorMessages; + $warning = ['code' => 'sandbox_sender', 'detail' => 'Sent from the test sender.']; + $this->reply(self::allQueued(['warnings' => [$warning]]), self::allQueued(['warnings' => [$warning]])); + + $result = $this->batch(self::recipients(150)); + + $codes = array_map(static fn($warning): string => $warning->getCode(), $result->getWarnings()); + $this->assertSame(['sandbox_sender'], $codes); + $this->assertSame([self::WARNING_LOGGED], $errorMessages); + } + + public function testWarningsReachTheCallerWhenALaterRequestFails(): void + { + global $errorMessages; + $warning = ['code' => 'sandbox_sender', 'detail' => 'Sent from the test sender.']; + $this->reply(self::allQueued(['warnings' => [$warning]]), self::wholeCall(429, 'quota_limited')); + + $error = $this->batchError(self::recipients(150)); + + $this->assertSame(['sandbox_sender'], array_map(static fn($w): string => $w->getCode(), $error->getWarnings())); + $this->assertSame([self::WARNING_LOGGED], $errorMessages); + } + + public static function setupErrors(): array + { + return [ + 'disabled' => [['isDisabled' => static fn(): bool => true], 'client_disabled'], + 'shut down' => [['isClosed' => static fn(): bool => true], 'client_closed'], + 'off Cloud without an app host' => [['host' => 'https://ph.example.com'], 'missing_app_host'], + 'no secret key' => [['secretKey' => ''], 'missing_secret_key'], + ]; + } + + #[DataProvider('setupErrors')] + public function testAClientThatCannotSendSendsNothing(array $config, string $code): void + { + $error = $this->refusal( + ['recipients' => self::recipients(1), 'template_id' => self::TEMPLATE_ID], + $this->emails($config) + ); + + $this->assertNotInstanceOf(EmailBatchError::class, $error); + $this->assertSame($code, $error->getErrorCode()); + $this->assertSame([], $this->requests); + } + + public static function refusedRecipientFields(): array + { + return [ + 'a position in the request' => ['recipients__37__idempotency_key', 'recipients__137__idempotency_key'], + 'a position alone' => ['recipients__37', 'recipients__137'], + 'not an ASCII number' => ["recipients__\u{00b2}__idempotency_key", "recipients__\u{00b2}__idempotency_key"], + 'past the request' => ['recipients__50__to', 'recipients'], + 'a huge number' => ['recipients__' . str_repeat('9', 5000) . '__idempotency_key', 'recipients'], + 'another field' => ['template_id', 'template_id'], + ]; + } + + #[DataProvider('refusedRecipientFields')] + public function testARefusedRecipientFieldNamesItsPositionInRecipients(string $attr, string $field): void + { + $this->reply(self::allQueued(), [400, json_encode([ + 'type' => 'validation_error', + 'code' => 'max_length', + 'detail' => 'Ensure this field has no more than 255 characters.', + 'attr' => $attr, + ]), []]); + + $error = $this->batchError(self::recipients(150)); + + $this->assertSame($field, $error->getField()); + $this->assertSame( + [...self::times(100, 'queued'), ...self::times(50, 'failed')], + self::statuses($error->getResults()) + ); + } +} From 6057be1f3c00912711b5173016542b3b66bee157 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:46:56 +0100 Subject: [PATCH 04/44] docs(emails): document emails()->batch() in the README Co-Authored-By: Claude Opus 5.5 --- README.md | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index fc592bd..b477a77 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ Existing span attributes take precedence. The processor preserves the applicatio ## Transactional email -`emails()` sends one email to one recipient, from an email template made transactional in PostHog or from content your code rendered, and reads what happened to it. +`emails()` sends one email to one recipient, or the same email to many recipients, one email each, from an email template made transactional in PostHog or from content your code rendered, and reads what happened to it. The client needs a project secret API key (`phs_...`) as `secretKey`. Create it with the "Send transactional email" preset (`transactional_email:write`) in your project settings, and add `transactional_email:read` if you read statuses with a key that can't send. Keys made with `hog_flow:write` still work. A client whose `host` is PostHog Cloud sends to its region's app host. For any other `host`, such as a reverse proxy, set the `app_host` option to your PostHog app host: email requests never go to a custom `host`. Loading flag definitions still sends the secret key to `host`, so when your proxy must not see the key, build the client with `loadFeatureFlags: false` and don't call `loadFlags()`: @@ -84,6 +84,32 @@ $status = PostHog::emails()->get($result->getId()); // queued, sent, delivered, - **Retries.** Network errors, rate limits and an unavailable service are retried up to `email_request_max_retries` times (default 2) with the same idempotency key, so a retry never sends twice. Each request times out after `email_request_timeout_ms` (default 15000). When a job runner already retries the send, pass `'max_retries' => 0` and an `idempotency_key` derived from what the email is for, such as `welcome:user_123`. A generated key does not survive a job retry. - **Moving from another provider.** Set the `migrated_from` option, such as `'resend'`, so PostHog knows where your sends came from. +### Batches + +`batch()` sends the same email to many recipients, one email each, and returns a result per recipient in the order of `recipients`: + +```php +$result = PostHog::emails()->batch([ + 'template_id' => '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b', + 'template_data' => ['team' => 'Analytics'], // shared by every recipient + 'recipients' => [ + ['to' => 'ada@example.com', 'template_data' => ['name' => 'Ada'], 'idempotency_key' => 'digest:ada'], + ['to' => 'alan@example.com', 'template_data' => ['name' => 'Alan'], 'idempotency_key' => 'digest:alan'], + ], +]); +foreach ($result->getResults() as $email) { + if ($email->getStatus() !== 'queued') { + echo $email->getTo(), ': ', $email->getStatus(), PHP_EOL; + } +} +``` + +- **Recipients.** Each recipient has `to` and optional `distinct_id`, `idempotency_key` and `template_data`. A recipient's `template_data` is merged over the shared `template_data`, and its keys replace the shared ones. With `template_key`, the content is the same for every recipient, so a recipient can't carry `template_data`. A batch takes no `cc`, `bcc`, `attachments` or `scheduled_at`: send those emails with `send()`. +- **Requests.** The client sends at most 100 recipients and 4 MiB of JSON per request, one request after another, and waits at least 45 seconds for each answer. +- **Idempotency keys.** Every retry reuses each recipient's key, so a retry never queues an email twice. Without a key, the client makes one that covers its own retries but not a second call. When a batch may be cut off and run again, pass keys you store: send it again with the same key within 24 hours, so it goes out once. Each recipient of a call needs a different key. +- **Statuses.** `getStatus()` is `queued` when PostHog accepted the email, `failed` when it refused it (`getError()` says why, such as a suppressed address), `unconfirmed` when the client can't tell, such as after a lost answer, and `not_attempted` when an earlier request of the batch failed. Send an `unconfirmed` email again with the same key within 24 hours, so it goes out once. `getWarnings()` holds PostHog's warnings, each once. +- **Errors.** A request that fails as a whole, such as a rate limit past its retries, stops the batch and throws `PostHog\EmailBatchError`, whose `getResults()` holds every recipient. After a lost answer, the client reads each email it may have queued by its key, and reports the ones PostHog has as `queued`. `batch_unavailable` (409) means the project can't send batches yet, and `not_found` (404) that the template doesn't exist or batch sends are off: send each email the batch didn't queue with `send()` and its recipient's `idempotency_key`. + ## Questions? ### [Join our Slack community.](https://join.slack.com/t/posthogusers/shared_invite/enQtOTY0MzU5NjAwMDY3LTc2MWQ0OTZlNjhkODk3ZDI3NDVjMDE1YjgxY2I4ZjI4MzJhZmVmNjJkN2NmMGJmMzc2N2U3Yjc3ZjI5NGFlZDQ) From 31113aa3e6c4f9c8b48c52d431b68db9946de3e9 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:41:47 +0100 Subject: [PATCH 05/44] fix(emails): keep batch emails unconfirmed after a read by key, build one body at a time A status read by key now fills in only the message ID: the recipient stays unconfirmed, since an email under the key may be a refusal or an older send. The client reads every unconfirmed email without a message ID at the end of each batch, on success too. A whole-request idempotency_key_in_flight leaves the request's recipients unconfirmed, and a later attempt's answer becomes their later error. The first malformed answer no longer sets a later error. The batch keeps each recipient's JSON and the requests' membership, and builds one request body at a time, reused for its retries. The results' own unconfirmed status replaces the separate maybe-queued map. Shared content over 4 MiB throws content_too_large naming html, text or template_data before any request, and a recipient too large alone names its template_data. A single send checks its form and content again before its idempotency key, as before the batch. The unused Emails::epochSecondsAsFloat is gone. Co-Authored-By: Claude Opus 5.5 --- lib/BatchEmailResult.php | 8 +- lib/EmailBatchError.php | 2 +- lib/Emails.php | 62 ++++---- lib/Internal/EmailBatch.php | 202 +++++++++++++++++--------- lib/Internal/EmailRecipient.php | 16 ++- test/EmailsBatchTest.php | 242 +++++++++++++++++++++++++++----- test/EmailsTest.php | 10 ++ 7 files changed, 405 insertions(+), 137 deletions(-) diff --git a/lib/BatchEmailResult.php b/lib/BatchEmailResult.php index be3fdb0..96d8af5 100644 --- a/lib/BatchEmailResult.php +++ b/lib/BatchEmailResult.php @@ -11,7 +11,8 @@ * - `failed`: PostHog didn't queue the email, and getError() says why, such as a suppressed address. * - `unconfirmed`: the client can't tell whether PostHog queued the email, such as after a lost answer. It may * still go out. Send it again with the same idempotency key within 24 hours, so it goes out once. - * getLaterError() holds what a retry in the same call answered, which describes only that retry. + * getMessageId() is the email's ID when PostHog answered one or has an email under the key. + * getLaterError() holds what a later attempt in the same call answered, which describes only that attempt. * - `not_attempted`: an earlier request of the batch failed, so the client sent nothing for this recipient. */ class BatchEmailResult @@ -65,8 +66,9 @@ public function getStatus(): string } /** - * The email's message ID when PostHog named it, also for some emails it didn't queue. Pass it to - * Emails::get() to read the email's status. + * The email's message ID when PostHog named it, also for some emails it didn't queue. For an `unconfirmed` + * email, it can be the ID of the email PostHog has under the recipient's key, which the client read at the end + * of the batch. Pass it to Emails::get() to read the email's status. */ public function getMessageId(): ?string { diff --git a/lib/EmailBatchError.php b/lib/EmailBatchError.php index 9cc561e..07dbb93 100644 --- a/lib/EmailBatchError.php +++ b/lib/EmailBatchError.php @@ -7,7 +7,7 @@ * * The code, message and other fields are that request's error. getResults() holds every recipient: those of * earlier requests as PostHog answered them, those of the failed request as `failed`, or `unconfirmed` where an - * earlier attempt may have queued them, and the rest as `not_attempted`. + * attempt may have queued them, and the rest as `not_attempted`. */ class EmailBatchError extends EmailError { diff --git a/lib/Emails.php b/lib/Emails.php index 46adaa5..75aac6c 100644 --- a/lib/Emails.php +++ b/lib/Emails.php @@ -419,32 +419,35 @@ public function get(string $messageId): EmailStatus * Each recipient's `idempotency_key` is 1 to 255 visible ASCII characters, a different one for each recipient * of the call, and every retry reuses it, so a retry never queues an email twice. 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: after a lost answer, the client reads the email by its key, and an earlier email with - * that key reads as this one, `queued`. + * and run again: a rerun within 24 hours replays the emails that went out instead of sending them twice. Make + * each key name one email of one run, such as `digest:2026-11-24:ada`. 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 would + * replay the earlier email instead of sending this one. * * Check each result's getStatus(): * * - `queued`: PostHog accepted the email. * - `failed`: PostHog refused it, and getError() says why, such as a suppressed address. - * - `unconfirmed`: the client can't tell whether PostHog accepted it, such as after a lost answer. Send it - * again with the same key within 24 hours, so it goes out once. + * - `unconfirmed`: the client can't tell whether PostHog accepted it, such as after a lost answer, or when + * another request still holds its key. Send it again with the same key within 24 hours, so it goes out once. * - `not_attempted`: an earlier request of the batch failed, so the client sent nothing for it. * * A request that fails as a whole, such as a rate limit past its retries, stops the batch and throws - * EmailBatchError, whose getResults() holds every recipient. After a lost answer, the client reads each email - * it may have queued by its key, and reports the ones PostHog has as `queued`. The code `batch_unavailable` - * (409) means the project can't send batches yet, and `not_found` (404) that the template doesn't exist or - * batch sends are off for the project: send each email the batch didn't queue with send() and its recipient's - * `idempotency_key`. + * EmailBatchError, whose getResults() holds every recipient. At the end of every batch, the client reads each + * `unconfirmed` email without a message ID by its key. When PostHog has the email, the recipient comes back + * still `unconfirmed`, with the email's getMessageId(). The code `batch_unavailable` (409) means the project + * can't send batches yet, and is never retried. `not_found` (404) means the template doesn't exist or batch + * sends are off for the project. For both, send each email the batch didn't queue with send() and its + * recipient's `idempotency_key`. Shared content over 4 MiB of JSON throws `content_too_large` before any + * request, and a recipient whose email alone is that large is `failed` with `content_too_large`. * * ```php + * $run = 'digest:' . date('Y-m-d'); * $result = $client->emails()->batch([ * 'template_id' => '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b', * 'recipients' => [ - * ['to' => 'ada@example.com', 'template_data' => ['name' => 'Ada'], 'idempotency_key' => 'digest:ada'], - * ['to' => 'alan@example.com', 'template_data' => ['name' => 'Alan'], 'idempotency_key' => 'digest:alan'], + * ['to' => 'ada@example.com', 'template_data' => ['name' => 'Ada'], 'idempotency_key' => "$run:ada"], + * ['to' => 'alan@example.com', 'template_data' => ['name' => 'Alan'], 'idempotency_key' => "$run:alan"], * ], * ]); * foreach ($result->getResults() as $email) { @@ -484,8 +487,8 @@ public function get(string $messageId): EmailStatus */ public function batch(array $batch): SendBatchResult { - [$shared, $isTemplateForm, $maxRetries] = $this->prepareBatch($batch); - $run = EmailBatch::prepare($shared, $batch['recipients'] ?? null, $isTemplateForm); + [$shared, $maxRetries] = $this->prepareBatch($batch); + $run = EmailBatch::prepare($shared, $batch['recipients'] ?? null); [$appHost, $secretKey] = $this->connect(self::SEND_NOT_DONE, self::SEND_KEY_NEEDED); try { $this->sendBatch($run, $appHost, $secretKey, $maxRetries); @@ -506,7 +509,7 @@ public function batch(array $batch): SendBatchResult private function prepareSend(array $email): array { $email = array_filter($email, static fn($value): bool => $value !== null); - [$to, $distinctId, $idempotencyKey] = EmailRecipient::check($email); + [$to, $distinctId] = EmailRecipient::address($email); $hasTemplateId = array_key_exists('template_id', $email); if ($hasTemplateId === array_key_exists('template_key', $email)) { throw new EmailError( @@ -515,6 +518,7 @@ private function prepareSend(array $email): array ); } [$payload, $files] = $hasTemplateId ? [self::templateContent($email), []] : self::codeContent($email); + $idempotencyKey = EmailRecipient::idempotencyKey($email); $maxRetries = $this->maxRetries($email); $scheduledAt = array_key_exists('scheduled_at', $email) ? self::scheduledAt($email['scheduled_at']) : null; $payload['to'] = $to; @@ -538,8 +542,7 @@ private function prepareSend(array $email): array } /** - * @return array{array, bool, int} The email every recipient gets, whether it is a template - * made in PostHog, and the retries of each request. + * @return array{array, int} The email every recipient gets, and the retries of each request. */ private function prepareBatch(array $batch): array { @@ -566,7 +569,7 @@ private function prepareBatch(array $batch): array unset($batch['recipients']); $shared = $isTemplateForm ? self::templateContent($batch, 'batch') : self::codeContent($batch, 'batch')[0]; - return [$shared, $isTemplateForm, $maxRetries]; + return [$shared, $maxRetries]; } private function maxRetries(array $call): int @@ -1136,14 +1139,15 @@ private function sendBatch(EmailBatch $run, string $appHost, string $secretKey, 'client_closed', "The PostHog client is shut down, so it didn't retry this request of the batch." ); + $url = $appHost . self::BATCH_PATH; for ($position = 0; $position < $run->requestCount(); $position++) { if ($position > 0 && ($this->isClosed)()) { throw $run->failure($run->closedAt($position)); } - $url = $appHost . self::BATCH_PATH; - $attemptOnce = function () use ($run, $position, $url, $headers, $timeoutMs): void { + $body = $run->requestBody($position); + $attemptOnce = function () use ($run, $position, $url, $headers, $body, $timeoutMs): void { try { - $reply = $this->request('POST', $url, $headers, $run->requestBody($position), $timeoutMs); + $reply = $this->request('POST', $url, $headers, $body, $timeoutMs); } catch (EmailError $error) { if (in_array($error->getErrorCode(), self::LOST_ANSWER_CODES, true)) { $run->lost($position); @@ -1156,16 +1160,17 @@ private function sendBatch(EmailBatch $run, string $appHost, string $secretKey, $this->withRetries($maxRetries, $attemptOnce, $closedBeforeARetry); } catch (EmailError $error) { $run->stop($position, $error); - $this->readLost($run, $appHost, $secretKey); + $this->readUnconfirmed($run, $appHost, $secretKey); throw $run->failure($error); } } + $this->readUnconfirmed($run, $appHost, $secretKey); } - private function readLost(EmailBatch $run, string $appHost, string $secretKey): void + private function readUnconfirmed(EmailBatch $run, string $appHost, string $secretKey): void { $headers = $this->headers($secretKey, []); - foreach ($run->keysToRead() as $index => $idempotencyKey) { + foreach ($run->unconfirmedWithoutMessageId() as $index => $idempotencyKey) { if (($this->isClosed)()) { return; } @@ -1180,7 +1185,7 @@ private function readLost(EmailBatch $run, string $appHost, string $secretKey): } return; } - $run->accepted($index, $status->getId()); + $run->found($index, $status->getId()); } } @@ -1322,11 +1327,6 @@ private static function wholeEpochSecondsAsFloat(DateTimeImmutable $time): float return (float) $time->format('U'); } - private static function epochSecondsAsFloat(DateTimeImmutable $time): float - { - return (float) $time->format('U.u'); - } - private static function onOneLogLine(string $text): string { return addcslashes($text, "\0..\37\177\\"); diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index 9f879ca..b621a97 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -13,7 +13,7 @@ /** * The recipients of one Emails::batch() call, split into requests, and what PostHog answered for each. * - * A recipient is maybe queued once PostHog may have queued its email: a request for it went unanswered, or + * A recipient is `unconfirmed` once PostHog may have queued its email: a request for it went unanswered, or * PostHog said it couldn't tell. It stays `unconfirmed` until PostHog answers `queued`, since a later refusal * doesn't prove the first attempt sent nothing. * @@ -25,25 +25,25 @@ final class EmailBatch private const MAX_REQUEST_BYTES = 4 * 1024 * 1024; private const RECIPIENT_FIELDS = ['to', 'distinct_id', 'idempotency_key', 'template_data']; private const UNCONFIRMED_CODES = ['idempotency_key_in_flight', 'delivery_unavailable', 'api_error']; + private const IN_FLIGHT = 'idempotency_key_in_flight'; private const JSON_FLAGS = JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE; private const SEND_SINGLY = "send each email the batch didn't queue with emails()->send() and its recipient's " . 'idempotency_key.'; - /** @var list}> */ + /** @var list> The positions in `recipients` that each request carries. */ private array $requests = []; /** @var array */ private array $results = []; - /** @var array */ - private array $maybeQueued = []; /** @var list */ private array $warnings = []; /** - * @param list $members + * @param list $members + * @param string $opening The request body up to its first recipient. */ - private function __construct(private array $members, string $emptyBody) + private function __construct(private array $members, private string $opening) { - $this->split($emptyBody); + $this->split(); } /** @@ -51,7 +51,7 @@ private function __construct(private array $members, string $emptyBody) * * @param array $shared The email every recipient gets, as the request carries it. */ - public static function prepare(array $shared, mixed $recipients, bool $isTemplateForm): self + public static function prepare(array $shared, mixed $recipients): self { if (!is_array($recipients) || $recipients === [] || !array_is_list($recipients)) { throw new EmailError( @@ -61,6 +61,11 @@ public static function prepare(array $shared, mixed $recipients, bool $isTemplat field: 'recipients' ); } + $emptyBody = self::encode([...$shared, 'recipients' => []], 'The email'); + if (strlen($emptyBody) > self::MAX_REQUEST_BYTES) { + throw self::sharedTooLarge($shared); + } + $isTemplateForm = array_key_exists('template_id', $shared); $members = []; $firstWithKey = []; foreach ($recipients as $index => $recipient) { @@ -78,11 +83,11 @@ public static function prepare(array $shared, mixed $recipients, bool $isTemplat $members[] = $member; } - return new self($members, self::encode([...$shared, 'recipients' => []], 'The email')); + return new self($members, substr($emptyBody, 0, -strlen(']}'))); } /** - * @return array{to: string, key: string, wire: string} + * @return array{to: string, key: string, wire: string, field: string} */ private static function member(int $index, mixed $recipient, bool $isTemplateForm): array { @@ -106,16 +111,23 @@ private static function member(int $index, mixed $recipient, bool $isTemplateFor ); } } - [$to, $distinctId, $key] = EmailRecipient::check($recipient, $index); - $wire = ['to' => $to, 'idempotency_key' => $key ?? Uuid::v4()]; + [$to, $distinctId] = EmailRecipient::address($recipient, $index); + $wire = ['to' => $to, 'idempotency_key' => EmailRecipient::idempotencyKey($recipient, $index) ?? Uuid::v4()]; if ($distinctId !== null) { $wire['distinct_id'] = $distinctId; } + $field = "recipients__$index"; if (array_key_exists('template_data', $recipient)) { $wire['message_data'] = self::templateData($index, $recipient['template_data'], $isTemplateForm); + $field .= '__template_data'; } - return ['to' => $to, 'key' => $wire['idempotency_key'], 'wire' => self::encode($wire, "recipients[$index]")]; + return [ + 'to' => $to, + 'key' => $wire['idempotency_key'], + 'wire' => self::encode($wire, "recipients[$index]"), + 'field' => $field, + ]; } private static function templateData(int $index, mixed $data, bool $isTemplateForm): array|object @@ -155,64 +167,71 @@ private static function encode(array $payload, string $what): string } /** - * Splits the recipients into requests of at most 100 recipients and 4 MiB, in order. A recipient too large for + * Puts the recipients in requests of at most 100 recipients and 4 MiB, in order. A recipient too large for * any request fails here and joins no request. */ - private function split(string $emptyBody): void + private function split(): void { + $emptyBytes = strlen($this->opening) + strlen(']}'); $indices = []; - $wires = []; - $bytes = strlen($emptyBody); + $bytes = $emptyBytes; foreach ($this->members as $index => $member) { $memberBytes = strlen($member['wire']); - if (strlen($emptyBody) + $memberBytes > self::MAX_REQUEST_BYTES) { - $this->set($index, 'failed', error: self::recipientTooLarge()); + if ($emptyBytes + $memberBytes > self::MAX_REQUEST_BYTES) { + $this->set($index, 'failed', error: self::recipientTooLarge($member['field'])); continue; } $separatorBytes = $indices === [] ? 0 : 1; $full = count($indices) === self::MAX_RECIPIENTS_PER_REQUEST; if ($indices !== [] && ($full || $bytes + $separatorBytes + $memberBytes > self::MAX_REQUEST_BYTES)) { - $this->addRequest($emptyBody, $indices, $wires); - [$indices, $wires, $bytes, $separatorBytes] = [[], [], strlen($emptyBody), 0]; + $this->requests[] = $indices; + [$indices, $bytes, $separatorBytes] = [[], $emptyBytes, 0]; } $indices[] = $index; - $wires[] = $member['wire']; $bytes += $separatorBytes + $memberBytes; } if ($indices !== []) { - $this->addRequest($emptyBody, $indices, $wires); + $this->requests[] = $indices; } } - /** - * @param list $indices - * @param list $wires - */ - private function addRequest(string $emptyBody, array $indices, array $wires): void - { - $withoutClosingBrackets = substr($emptyBody, 0, -strlen(']}')); - $this->requests[] = ['body' => $withoutClosingBrackets . implode(',', $wires) . ']}', 'indices' => $indices]; - } - public function requestCount(): int { return count($this->requests); } + /** + * Builds the body of request `$position`. Every attempt of the request sends this same body. + */ public function requestBody(int $position): string { - return $this->requests[$position]['body']; + $wires = array_map(fn(int $index): string => $this->members[$index]['wire'], $this->requests[$position]); + + return $this->opening . implode(',', $wires) . ']}'; } /** * An attempt of request `$position` got no answer the client can read, so it may have queued any of its * recipients. + * + * @param EmailError|null $laterError What the attempt answered, kept as the later error of a recipient an + * earlier attempt already left `unconfirmed`. */ - public function lost(int $position): void + public function lost(int $position, ?EmailError $laterError = null): void { - foreach ($this->requests[$position]['indices'] as $index) { - $this->maybeQueued[$index] = true; - $messageId = ($this->results[$index] ?? null)?->getMessageId(); + foreach ($this->requests[$position] as $index) { + $earlier = $this->results[$index] ?? null; + if ($laterError !== null && $this->isUnconfirmed($index)) { + $this->set( + $index, + 'unconfirmed', + $earlier->getMessageId(), + error: $earlier->getError(), + laterError: $laterError + ); + continue; + } + $messageId = $earlier?->getMessageId(); $this->set($index, 'unconfirmed', $messageId, error: self::unconfirmed($messageId)); } } @@ -225,13 +244,18 @@ public function lost(int $position): void */ public function answer(int $position, int $status, string $body, array $headers): void { - $indices = $this->requests[$position]['indices']; + $indices = $this->requests[$position]; $fields = EmailReplies::fields($body); if ($status < 200 || $status >= 300) { + $error = self::requestError($fields, $status, $headers, $indices); if ($status >= 500) { $this->lost($position); + } elseif ($error->getErrorCode() === self::IN_FLIGHT) { + $this->lost($position, $error); + } else { + $this->refusedLater($position, $error); } - throw self::requestError($fields, $status, $headers, $indices); + throw $error; } $slots = $fields['results'] ?? null; if (!is_array($slots) || !array_is_list($slots) || count($slots) !== count($indices)) { @@ -252,6 +276,22 @@ public function answer(int $position, int $status, string $body, array $headers) } } + private function refusedLater(int $position, EmailError $error): void + { + foreach ($this->requests[$position] as $index) { + if ($this->isUnconfirmed($index)) { + $earlier = $this->results[$index]; + $this->set( + $index, + 'unconfirmed', + $earlier->getMessageId(), + error: $earlier->getError(), + laterError: $error + ); + } + } + } + /** * @param array $slot */ @@ -264,12 +304,11 @@ private function settle(int $index, array $slot): void return; } $answer = self::slotError($error, $messageId); - if (isset($this->maybeQueued[$index])) { + if ($this->isUnconfirmed($index)) { $earlier = $this->results[$index]; $messageId ??= $earlier->getMessageId(); $this->set($index, 'unconfirmed', $messageId, error: $earlier->getError(), laterError: $answer); } elseif (in_array($answer->getErrorCode(), self::UNCONFIRMED_CODES, true)) { - $this->maybeQueued[$index] = true; $this->set($index, 'unconfirmed', $messageId, error: $answer); } else { $this->set($index, 'failed', $messageId, error: $answer); @@ -281,20 +320,9 @@ private function settle(int $index, array $slot): void */ public function stop(int $position, EmailError $error): void { - $status = $error->getStatusCode(); - $later = $status !== null && $status < 500 ? $error : null; - foreach ($this->requests[$position]['indices'] as $index) { - if (!isset($this->maybeQueued[$index])) { + foreach ($this->requests[$position] as $index) { + if (!$this->isUnconfirmed($index)) { $this->set($index, 'failed', error: $error); - } elseif ($later !== null) { - $earlier = $this->results[$index]; - $this->set( - $index, - 'unconfirmed', - $earlier->getMessageId(), - error: $earlier->getError(), - laterError: $later - ); } } $this->skipFrom($position + 1, new EmailError( @@ -319,23 +347,23 @@ public function closedAt(int $position): EmailError private function skipFrom(int $position, EmailError $error): void { - foreach (array_slice($this->requests, $position) as $request) { - foreach ($request['indices'] as $index) { + foreach (array_slice($this->requests, $position) as $indices) { + foreach ($indices as $index) { $this->set($index, 'not_attempted', error: $error); } } } /** - * @return array The idempotency key of each recipient a lost answer left without a message ID, - * by its position in `recipients`. + * @return array The idempotency key of each `unconfirmed` recipient without a message ID, by its + * position in `recipients`. */ - public function keysToRead(): array + public function unconfirmedWithoutMessageId(): array { $keys = []; - foreach ($this->maybeQueued as $index => $_) { - if ($this->results[$index]->getMessageId() === null) { - $keys[$index] = $this->members[$index]['key']; + foreach ($this->results as $index => $result) { + if ($result->getStatus() === 'unconfirmed' && $result->getMessageId() === null) { + $keys[$index] = $result->getIdempotencyKey(); } } ksort($keys); @@ -343,9 +371,20 @@ public function keysToRead(): array return $keys; } - public function accepted(int $index, string $messageId): void + /** + * PostHog has an email under the recipient's key. That shows neither that this call queued it nor that it + * goes out, so the recipient stays `unconfirmed`, now with the email's ID. + */ + public function found(int $index, string $messageId): void { - $this->set($index, 'queued', $messageId); + $result = $this->results[$index]; + $this->set( + $index, + 'unconfirmed', + $messageId, + error: $result->getError(), + laterError: $result->getLaterError() + ); } public function result(): SendBatchResult @@ -358,6 +397,11 @@ public function failure(EmailError $error): EmailBatchError return new EmailBatchError($error, $this->outcome(), $this->warnings); } + private function isUnconfirmed(int $index): bool + { + return ($this->results[$index] ?? null)?->getStatus() === 'unconfirmed'; + } + /** * @return list */ @@ -467,13 +511,37 @@ private static function unconfirmed(?string $messageId): EmailError ); } - private static function recipientTooLarge(): EmailError + /** + * @param array $shared + */ + private static function sharedTooLarge(array $shared): EmailError + { + $sizes = []; + foreach (['html', 'text', 'subject'] as $field) { + if (is_string($shared[$field] ?? null)) { + $sizes[$field] = strlen($shared[$field]); + } + } + arsort($sizes); + $field = array_key_exists('template_id', $shared) ? 'template_data' : (string) array_key_first($sizes); + + return new EmailError( + 'content_too_large', + "The $field every recipient of the batch gets is larger than one batch request takes (4 MiB of JSON), " + . 'so no email was sent.', + fix: "Make $field smaller, such as by linking to images instead of embedding them, or send each email " + . 'with emails()->send().', + field: $field + ); + } + + private static function recipientTooLarge(string $field): EmailError { return new EmailError( 'content_too_large', "This recipient's email is larger than one batch request takes, so it wasn't sent.", fix: "Send this recipient's email with emails()->send().", - field: 'recipients' + field: $field ); } } diff --git a/lib/Internal/EmailRecipient.php b/lib/Internal/EmailRecipient.php index 7fe502b..dfdca10 100644 --- a/lib/Internal/EmailRecipient.php +++ b/lib/Internal/EmailRecipient.php @@ -16,9 +16,9 @@ final class EmailRecipient /** * @param array $fields The recipient's fields, without nulls. * @param int|null $index The recipient's position in a batch's `recipients`, or null for a single send. - * @return array{string, ?string, ?string} The address, the distinct ID and the idempotency key. + * @return array{string, ?string} The address and the distinct ID. */ - public static function check(array $fields, ?int $index = null): array + public static function address(array $fields, ?int $index = null): array { $to = $fields['to'] ?? null; if (!is_string($to) || trim($to) === '') { @@ -29,6 +29,16 @@ public static function check(array $fields, ?int $index = null): array if ($distinctId !== null && (!is_string($distinctId) || $distinctId === '')) { throw self::invalid('invalid_distinct_id', 'distinct_id must be a nonempty string.', 'distinct_id', $index); } + + return [$to, $distinctId]; + } + + /** + * @param array $fields The recipient's fields, without nulls. + * @param int|null $index The recipient's position in a batch's `recipients`, or null for a single send. + */ + public static function idempotencyKey(array $fields, ?int $index = null): ?string + { $idempotencyKey = $fields['idempotency_key'] ?? null; if ( $idempotencyKey !== null @@ -42,7 +52,7 @@ public static function check(array $fields, ?int $index = null): array ); } - return [$to, $distinctId, $idempotencyKey]; + return $idempotencyKey; } private static function invalid(string $code, string $message, string $field, ?int $index): EmailError diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index 67bfbd2..851fcfd 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -3,6 +3,8 @@ namespace PostHog\Test; use Closure; +use DateTimeImmutable; +use DateTimeZone; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use PostHog\BatchEmailResult; @@ -12,6 +14,8 @@ use PostHog\SendBatchResult; use stdClass; use Symfony\Component\Clock\Clock; +use Symfony\Component\Clock\ClockInterface; +use Symfony\Component\Clock\MockClock; class EmailsBatchTest extends TestCase { @@ -107,16 +111,31 @@ private static function wholeCall(int $status, ?string $code = null): array } /** @return array{int, string, list} */ - private static function statusFound(string $messageId): array + private static function statusFound(string $messageId, string $status = 'sent', ?string $reason = null): array { return [200, json_encode([ 'id' => $messageId, - 'status' => 'sent', + 'status' => $status, 'created_at' => '2026-11-02T10:00:00Z', 'status_at' => '2026-11-02T10:00:01Z', + 'reason' => $reason, ]), []]; } + /** @return array */ + private static function notConfirmed(?string $messageId = 'm0'): array + { + return array_filter([ + 'message_id' => $messageId, + 'error' => [ + 'code' => 'delivery_unavailable', + 'detail' => 'Not confirmed.', + 'status' => 503, + 'retryable' => true, + ], + ]); + } + /** A server that answers after this many seconds: a request with a shorter timeout gets no answer. */ private static function slow(int $seconds, Closure $answer): Closure { @@ -287,11 +306,9 @@ public function testATemplateBatchWithoutDataSendsAnEmptyObject(): void $this->batch([['to' => 'a@example.com', 'idempotency_key' => 'k', 'template_data' => []]]); - $this->assertSame( - '{"template_id":"' . self::TEMPLATE_ID . '","message_data":{},"recipients":' - . '[{"to":"a@example.com","idempotency_key":"k","message_data":{}}]}', - $this->requests[0]['body'] - ); + $body = json_decode($this->requests[0]['body'], flags: JSON_THROW_ON_ERROR); + $this->assertEquals(new stdClass(), $body->message_data); + $this->assertEquals(new stdClass(), $body->recipients[0]->message_data); } public function testACodeBatchSendsTheSameContentToEveryRecipient(): void @@ -474,7 +491,7 @@ public function testSplitsByThe4MibBodyAndFailsOnlyARecipientTooLargeAlone(): vo $results = $result->getResults(); $this->assertSame(['queued', 'queued', 'queued', 'failed', 'queued'], self::statuses($results)); $tooLarge = $results[3]; - $this->assertSame(['content_too_large', 'recipients', 'validation_error'], [ + $this->assertSame(['content_too_large', 'recipients__3__template_data', 'validation_error'], [ $tooLarge->getError()->getErrorCode(), $tooLarge->getError()->getField(), $tooLarge->getError()->getErrorName(), @@ -482,6 +499,51 @@ public function testSplitsByThe4MibBodyAndFailsOnlyARecipientTooLargeAlone(): vo $this->assertSame([null, 'key-3'], [$tooLarge->getMessageId(), $tooLarge->getIdempotencyKey()]); } + public static function sharedContentOver4Mib(): array + { + $over = str_repeat('x', self::FOUR_MIB); + + return [ + 'html' => [['template_key' => 'news', 'subject' => 'News', 'html' => $over, 'text' => 'Hi'], 'html'], + 'text' => [['template_key' => 'news', 'subject' => 'News', 'html' => '

Hi

', 'text' => $over], 'text'], + 'template_data' => [ + ['template_id' => self::TEMPLATE_ID, 'template_data' => ['note' => $over]], + 'template_data', + ], + ]; + } + + #[DataProvider('sharedContentOver4Mib')] + public function testSharedContentOver4MibIsRefusedBeforeAnyRequest(array $content, string $field): void + { + $error = $this->refusal(['recipients' => self::recipients(2), ...$content]); + + $this->assertNotInstanceOf(EmailBatchError::class, $error); + $this->assertSame(['content_too_large', $field, 'validation_error'], [ + $error->getErrorCode(), + $error->getField(), + $error->getErrorName(), + ]); + $this->assertSame([], $this->requests); + } + + public function testHoldsOneRequestBodyAtATime(): void + { + $recipients = self::recipients(3000); + $usageAtTheFirstRequest = 0; + $this->reply(function (string $url, string $body) use (&$usageAtTheFirstRequest): array { + $usageAtTheFirstRequest = memory_get_usage(); + + return self::allQueued()($url, $body); + }, ...array_fill(0, 29, self::allQueued())); + $usageBefore = memory_get_usage(); + + $this->batch($recipients, ['template_data' => ['note' => str_repeat('x', 200_000)]]); + + $this->assertSame(array_fill(0, 30, 100), $this->recipientsPerRequest()); + $this->assertLessThan(5_000_000, $usageAtTheFirstRequest - $usageBefore); + } + public static function requestsAtTheLimit(): array { return [ @@ -534,12 +596,17 @@ public function testARetryAfterALostAnswerKeepsARefusedRecipientUnconfirmed(): v self::networkError(), self::ok(self::queued('m0', true), self::refused('m1', 'idempotency_key_reused')) ); + $recipients = self::recipients(2); + unset($recipients[1]['idempotency_key']); - $result = $this->batch(self::recipients(2)); + $result = $this->batch($recipients); $this->assertCount(2, $this->requests); - $this->assertSame($this->requests[0]['body'], $this->requests[1]['body']); + $this->assertSame($this->body(0), $this->body(1)); + $derived = $this->body(1)['recipients'][1]['idempotency_key']; + $this->assertMatchesRegularExpression(self::UUID_V4, $derived); [$first, $second] = $result->getResults(); + $this->assertSame($derived, $second->getIdempotencyKey()); $this->assertSame(['queued', 'm0', true], [$first->getStatus(), $first->getMessageId(), $first->isReplayed()]); $this->assertSame(['unconfirmed', 'm1'], [$second->getStatus(), $second->getMessageId()]); $this->assertSame('delivery_unavailable', $second->getError()->getErrorCode()); @@ -561,34 +628,95 @@ public function testAnAnswerTooLargeToReadLeavesTheRequestUnconfirmed(): void $this->assertSame(['key-0'], $this->readsByKey()); } - public function testA503ThenARefusalAlsoKeepsTheRecipientUnconfirmed(): void + public function testA503ThenARefusalOfTheWholeRequestKeepsTheRecipientUnconfirmed(): void { - $this->reply(self::wholeCall(503, 'delivery_unavailable'), self::ok(self::refused('m0', 'sending_paused'))); + $notFound = self::wholeCall(404, 'not_found'); + $this->reply(self::wholeCall(503, 'delivery_unavailable'), self::wholeCall(422, 'sending_paused'), $notFound); - [$result] = $this->batch(self::recipients(1))->getResults(); + $error = $this->batchError(self::recipients(1)); + $this->assertSame(['sending_paused', 422], [$error->getErrorCode(), $error->getStatusCode()]); + [$result] = $error->getResults(); $this->assertSame('unconfirmed', $result->getStatus()); + $this->assertSame('delivery_unavailable', $result->getError()->getErrorCode()); $this->assertSame('sending_paused', $result->getLaterError()->getErrorCode()); } - public static function answersThatMayStillGoOut(): array + public function testARecipientThePipelineDidNotConfirmIsUnconfirmed(): void + { + $this->reply(self::ok(self::notConfirmed())); + + [$result] = $this->batch(self::recipients(1))->getResults(); + + $this->assertSame(['unconfirmed', 'm0'], [$result->getStatus(), $result->getMessageId()]); + $this->assertSame(['delivery_unavailable', 503], [ + $result->getError()->getErrorCode(), + $result->getError()->getStatusCode(), + ]); + $this->assertNull($result->getLaterError()); + } + + public function testABatchThatSucceedsReadsEachUnconfirmedEmailWithoutAMessageId(): void + { + $this->reply( + self::ok(self::queued('m0'), self::notConfirmed(null), self::notConfirmed('m2')), + self::statusFound('m1') + ); + + $result = $this->batch(self::recipients(3), ['max_retries' => 0]); + + $this->assertSame(['key-1'], $this->readsByKey()); + $this->assertSame( + [['queued', 'm0'], ['unconfirmed', 'm1'], ['unconfirmed', 'm2']], + array_map(static fn($r): array => [$r->getStatus(), $r->getMessageId()], $result->getResults()) + ); + } + + public function testAWholeRequestInFlightAnswerLeavesItsRecipientsUnconfirmed(): void + { + $this->reply(self::wholeCall(409, 'idempotency_key_in_flight'), self::statusFound('m0'), self::wholeCall(404)); + + $error = $this->batchError(self::recipients(2), ['max_retries' => 0]); + + $this->assertSame('idempotency_key_in_flight', $error->getErrorCode()); + $this->assertSame( + [['unconfirmed', 'm0', null], ['unconfirmed', null, null]], + array_map( + static fn($r): array => [$r->getStatus(), $r->getMessageId(), $r->getLaterError()], + $error->getResults() + ) + ); + $this->assertSame(['key-0', 'key-1'], $this->readsByKey()); + } + + public static function attemptsAfterAnInFlightAnswer(): array { return [ - 'not confirmed by the pipeline' => [self::refused('m0', 'delivery_unavailable', 503, true)], - 'held by another request' => [self::refused('m0', 'idempotency_key_in_flight', 409, true)], + 'a refusal after an in-flight answer' => [ + [self::wholeCall(409, 'idempotency_key_in_flight'), self::wholeCall(429, 'quota_limited')], + 'quota_limited', + ], + 'an in-flight answer after a 503' => [ + [self::wholeCall(503, 'delivery_unavailable'), self::wholeCall(409, 'idempotency_key_in_flight')], + 'idempotency_key_in_flight', + ], ]; } - #[DataProvider('answersThatMayStillGoOut')] - public function testARecipientPostHogMayStillSendIsUnconfirmed(array $answer): void - { - $this->reply(self::ok($answer)); + #[DataProvider('attemptsAfterAnInFlightAnswer')] + public function testTheAttemptAfterTheOneThatLeftARecipientUnconfirmedIsItsLaterError( + array $answers, + string $laterCode + ): void { + $this->reply(...$answers, ...[self::wholeCall(404)]); - [$result] = $this->batch(self::recipients(1))->getResults(); + $error = $this->batchError(self::recipients(1), ['max_retries' => 1]); - $this->assertSame(['unconfirmed', 'm0'], [$result->getStatus(), $result->getMessageId()]); - $this->assertSame($answer['error']['code'], $result->getError()->getErrorCode()); - $this->assertNull($result->getLaterError()); + [$result] = $error->getResults(); + $this->assertSame('unconfirmed', $result->getStatus()); + $this->assertSame('delivery_unavailable', $result->getError()->getErrorCode()); + $this->assertSame($laterCode, $result->getLaterError()->getErrorCode()); + $this->assertCount(3, $this->requests); } public function testAShutdownDuringABatchStopsItBeforeTheNextRequest(): void @@ -612,16 +740,16 @@ public function testAShutdownDuringABatchStopsItBeforeTheNextRequest(): void public function testAShutdownDuringARetryWaitSendsNoRetry(): void { - $this->reply(function (): array { + Clock::set(self::clockThatShutsDownOnSleep($this->clock, function (): void { $this->closed = true; - - return self::wholeCall(429); - }, self::allQueued()); + })); + $this->reply(self::wholeCall(429), self::allQueued()); $error = $this->batchError(self::recipients(150), emails: $this->closedEmails()); $this->assertSame('client_closed', $error->getErrorCode()); $this->assertCount(1, $this->requests); + $this->assertTrue($this->closed); $this->assertSame( [...self::times(100, 'failed'), ...self::times(50, 'not_attempted')], self::statuses($error->getResults()) @@ -629,6 +757,31 @@ public function testAShutdownDuringARetryWaitSendsNoRetry(): void $this->assertSame('client_closed', $error->getResults()[0]->getError()->getErrorCode()); } + private static function clockThatShutsDownOnSleep(MockClock $clock, Closure $shutDown): ClockInterface + { + return new class ($clock, $shutDown) implements ClockInterface { + public function __construct(private MockClock $clock, private Closure $shutDown) + { + } + + public function now(): DateTimeImmutable + { + return $this->clock->now(); + } + + public function sleep(float|int $seconds): void + { + ($this->shutDown)(); + $this->clock->sleep($seconds); + } + + public function withTimeZone(DateTimeZone|string $timezone): static + { + return $this; + } + }; + } + public function testAShutdownBeforeALostAnswerReadsNoEmailByItsKey(): void { $this->reply(function (): array { @@ -671,12 +824,12 @@ public function testARequestRefusedAsAWholeThrowsWithTheResultsSoFar(): void public function testARefusalOfTheWholeRequestAfterALostAnswerKeepsItsRecipientsUnconfirmed(): void { - $this->reply(self::networkError(), self::wholeCall(429, 'quota_limited'), self::wholeCall(404, 'not_found')); + $this->reply(self::networkError(), self::wholeCall(429, 'quota_limited'), self::statusFound('m0')); $error = $this->batchError(self::recipients(1)); [$result] = $error->getResults(); - $this->assertSame('unconfirmed', $result->getStatus()); + $this->assertSame(['unconfirmed', 'm0'], [$result->getStatus(), $result->getMessageId()]); $this->assertSame('delivery_unavailable', $result->getError()->getErrorCode()); $this->assertSame('quota_limited', $result->getLaterError()->getErrorCode()); $this->assertSame(['key-0'], $this->readsByKey()); @@ -694,12 +847,33 @@ public function testALostAnswerAfterTheRetriesReadsEachEmailByItsKey(): void $this->assertSame('network_error', $error->getErrorCode()); $this->assertSame(['key-0', 'key-1'], $this->readsByKey()); $this->assertSame( - [['queued', 'm0'], ['unconfirmed', null]], + [['unconfirmed', 'm0'], ['unconfirmed', null]], array_map(static fn($r): array => [$r->getStatus(), $r->getMessageId()], $error->getResults()) ); $this->assertSame('delivery_unavailable', $error->getResults()[1]->getError()->getErrorCode()); } + public static function statusesReadByKey(): array + { + return [ + 'sent' => [self::statusFound('m0')], + 'refused' => [self::statusFound('m0', 'failed', 'recipient_suppressed')], + ]; + } + + #[DataProvider('statusesReadByKey')] + public function testAStatusReadByKeyFillsInOnlyTheMessageId(array $read): void + { + $this->reply(self::networkError(), $read); + + $error = $this->batchError(self::recipients(1), ['max_retries' => 0]); + + [$result] = $error->getResults(); + $this->assertSame(['unconfirmed', 'm0'], [$result->getStatus(), $result->getMessageId()]); + $this->assertSame('delivery_unavailable', $result->getError()->getErrorCode()); + $this->assertNull($result->getLaterError()); + } + public function testAnEmailWithAMessageIdIsNotReadByItsKey(): void { $this->reply( @@ -739,7 +913,7 @@ public function testBatchUnavailableIsNotRetriedAndSaysToSendEachEmailOnItsOwn() { $this->reply(self::wholeCall(409, 'batch_unavailable')); - $error = $this->batchError(self::recipients(2)); + $error = $this->batchError(self::recipients(2), ['max_retries' => 2]); $this->assertCount(1, $this->requests); $this->assertSame('batch_unavailable', $error->getErrorCode()); @@ -776,6 +950,10 @@ public function testAnAnswerWithoutAResultPerRecipientLeavesTheRequestUnconfirme $this->assertSame('api_error', $error->getErrorCode()); $this->assertSame(['unconfirmed', 'unconfirmed'], self::statuses($error->getResults())); + $this->assertSame( + [null, null], + array_map(static fn($r): ?EmailError => $r->getLaterError(), $error->getResults()) + ); $this->assertSame(['key-0', 'key-1'], $this->readsByKey()); } diff --git a/test/EmailsTest.php b/test/EmailsTest.php index 76e3319..c4bc144 100644 --- a/test/EmailsTest.php +++ b/test/EmailsTest.php @@ -998,6 +998,16 @@ public static function argumentErrors(): array 'invalid_idempotency_key', 'idempotency_key', ], + 'no form and a bad idempotency key' => [ + ['to' => 'user@example.com', 'idempotency_key' => 'welcome user'], + 'invalid_form', + null, + ], + 'empty subject and a bad idempotency key' => [ + ['subject' => '', 'idempotency_key' => 'welcome user'] + $code, + 'invalid_form', + 'subject', + ], 'negative max_retries' => [$template + ['max_retries' => -1], 'invalid_max_retries', 'max_retries'], 'max_retries as a string' => [$template + ['max_retries' => '1'], 'invalid_max_retries', 'max_retries'], 'html with invalid UTF-8' => [['html' => "\xB1\x31"] + $code, 'invalid_form', null], From f4a9e965e5c8a45d9d09dadc1af7acb9f3f1f6c9 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:41:47 +0100 Subject: [PATCH 06/44] docs(emails): use per-run keys in the batch example, warn against reusing a key The README's batch example names one email of one run with each key, says never to reuse a key for another email, and says that unconfirmed emails come back with their message ID when PostHog has them. Co-Authored-By: Claude Opus 5.5 --- README.md | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index b477a77..70a0456 100644 --- a/README.md +++ b/README.md @@ -89,12 +89,13 @@ $status = PostHog::emails()->get($result->getId()); // queued, sent, delivered, `batch()` sends the same email to many recipients, one email each, and returns a result per recipient in the order of `recipients`: ```php +$run = 'digest:' . date('Y-m-d'); // one key per email of this run $result = PostHog::emails()->batch([ 'template_id' => '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b', 'template_data' => ['team' => 'Analytics'], // shared by every recipient 'recipients' => [ - ['to' => 'ada@example.com', 'template_data' => ['name' => 'Ada'], 'idempotency_key' => 'digest:ada'], - ['to' => 'alan@example.com', 'template_data' => ['name' => 'Alan'], 'idempotency_key' => 'digest:alan'], + ['to' => 'ada@example.com', 'template_data' => ['name' => 'Ada'], 'idempotency_key' => "$run:ada"], + ['to' => 'alan@example.com', 'template_data' => ['name' => 'Alan'], 'idempotency_key' => "$run:alan"], ], ]); foreach ($result->getResults() as $email) { @@ -105,10 +106,10 @@ foreach ($result->getResults() as $email) { ``` - **Recipients.** Each recipient has `to` and optional `distinct_id`, `idempotency_key` and `template_data`. A recipient's `template_data` is merged over the shared `template_data`, and its keys replace the shared ones. With `template_key`, the content is the same for every recipient, so a recipient can't carry `template_data`. A batch takes no `cc`, `bcc`, `attachments` or `scheduled_at`: send those emails with `send()`. -- **Requests.** The client sends at most 100 recipients and 4 MiB of JSON per request, one request after another, and waits at least 45 seconds for each answer. -- **Idempotency keys.** Every retry reuses each recipient's key, so a retry never queues an email twice. Without a key, the client makes one that covers its own retries but not a second call. When a batch may be cut off and run again, pass keys you store: send it again with the same key within 24 hours, so it goes out once. Each recipient of a call needs a different key. -- **Statuses.** `getStatus()` is `queued` when PostHog accepted the email, `failed` when it refused it (`getError()` says why, such as a suppressed address), `unconfirmed` when the client can't tell, such as after a lost answer, and `not_attempted` when an earlier request of the batch failed. Send an `unconfirmed` email again with the same key within 24 hours, so it goes out once. `getWarnings()` holds PostHog's warnings, each once. -- **Errors.** A request that fails as a whole, such as a rate limit past its retries, stops the batch and throws `PostHog\EmailBatchError`, whose `getResults()` holds every recipient. After a lost answer, the client reads each email it may have queued by its key, and reports the ones PostHog has as `queued`. `batch_unavailable` (409) means the project can't send batches yet, and `not_found` (404) that the template doesn't exist or batch sends are off: send each email the batch didn't queue with `send()` and its recipient's `idempotency_key`. +- **Requests.** The client sends at most 100 recipients and 4 MiB of JSON per request, one request after another, and waits at least 45 seconds for each answer. Shared content over 4 MiB throws `content_too_large` before any request. A recipient whose email alone is over 4 MiB is `failed` with `content_too_large`. +- **Idempotency keys.** Every retry reuses each recipient's key, so a retry never queues an email twice. Without a key, the client makes one that covers its own retries but not a second call. When a batch may be cut off and run again, pass keys you store: send it again with the same key within 24 hours, so it goes out once. Each recipient of a call needs a different key. Make each key name one email of one run, such as `digest:2026-11-24:ada`. Never reuse a key for another email: PostHog would replay the earlier email instead of sending this one. +- **Statuses.** `getStatus()` is `queued` when PostHog accepted the email, `failed` when it refused it (`getError()` says why, such as a suppressed address), `unconfirmed` when the client can't tell, such as after a lost answer, and `not_attempted` when an earlier request of the batch failed. At the end of every batch, the client reads each `unconfirmed` email without a message ID by its key. When PostHog has the email, the recipient comes back still `unconfirmed`, with its `getMessageId()`. Send each `unconfirmed` email again with the same key within 24 hours, so it goes out once. `getWarnings()` holds PostHog's warnings, each once. +- **Errors.** A request that fails as a whole, such as a rate limit past its retries, stops the batch and throws `PostHog\EmailBatchError`, whose `getResults()` holds every recipient. `batch_unavailable` (409) means the project can't send batches yet, and is never retried. `not_found` (404) means the template doesn't exist or batch sends are off. For both, send each email the batch didn't queue with `send()` and its recipient's `idempotency_key`. ## Questions? From 3dfd017e9de080c75d86f903468e6607a4d701fb Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:44:07 +0100 Subject: [PATCH 07/44] chore(emails): drop the prose comments from the internal batch classes Co-Authored-By: Claude Opus 5.5 --- lib/Internal/EmailBatch.php | 34 --------------------------------- lib/Internal/EmailRecipient.php | 2 -- lib/Internal/EmailReplies.php | 2 -- 3 files changed, 38 deletions(-) diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index b621a97..6928d50 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -11,12 +11,6 @@ use PostHog\Uuid; /** - * The recipients of one Emails::batch() call, split into requests, and what PostHog answered for each. - * - * A recipient is `unconfirmed` once PostHog may have queued its email: a request for it went unanswered, or - * PostHog said it couldn't tell. It stays `unconfirmed` until PostHog answers `queued`, since a later refusal - * doesn't prove the first attempt sent nothing. - * * @internal */ final class EmailBatch @@ -47,8 +41,6 @@ private function __construct(private array $members, private string $opening) } /** - * Checks every recipient before any request, and gives each the idempotency key its every attempt carries. - * * @param array $shared The email every recipient gets, as the request carries it. */ public static function prepare(array $shared, mixed $recipients): self @@ -166,10 +158,6 @@ private static function encode(array $payload, string $what): string } } - /** - * Puts the recipients in requests of at most 100 recipients and 4 MiB, in order. A recipient too large for - * any request fails here and joins no request. - */ private function split(): void { $emptyBytes = strlen($this->opening) + strlen(']}'); @@ -200,9 +188,6 @@ public function requestCount(): int return count($this->requests); } - /** - * Builds the body of request `$position`. Every attempt of the request sends this same body. - */ public function requestBody(int $position): string { $wires = array_map(fn(int $index): string => $this->members[$index]['wire'], $this->requests[$position]); @@ -211,9 +196,6 @@ public function requestBody(int $position): string } /** - * An attempt of request `$position` got no answer the client can read, so it may have queued any of its - * recipients. - * * @param EmailError|null $laterError What the attempt answered, kept as the later error of a recipient an * earlier attempt already left `unconfirmed`. */ @@ -237,9 +219,6 @@ public function lost(int $position, ?EmailError $laterError = null): void } /** - * Records PostHog's answer to request `$position`. Throws the request's error when PostHog refused the whole - * request or its answer can't be read. - * * @param list $headers */ public function answer(int $position, int $status, string $body, array $headers): void @@ -315,9 +294,6 @@ private function settle(int $index, array $slot): void } } - /** - * Request `$position` failed as a whole, so the batch stops there. - */ public function stop(int $position, EmailError $error): void { foreach ($this->requests[$position] as $index) { @@ -331,9 +307,6 @@ public function stop(int $position, EmailError $error): void )); } - /** - * The client shut down before request `$position` went out. - */ public function closedAt(int $position): EmailError { $error = new EmailError( @@ -371,10 +344,6 @@ public function unconfirmedWithoutMessageId(): array return $keys; } - /** - * PostHog has an email under the recipient's key. That shows neither that this call queued it nor that it - * goes out, so the recipient stays `unconfirmed`, now with the email's ID. - */ public function found(int $index, string $messageId): void { $result = $this->results[$index]; @@ -463,9 +432,6 @@ private static function requestError(array $fields, int $status, array $headers, } /** - * PostHog names a recipient by its position in the request. The caller knows it by its position in - * `recipients`. - * * @param list $indices */ private static function recipientsField(string $attr, array $indices): string diff --git a/lib/Internal/EmailRecipient.php b/lib/Internal/EmailRecipient.php index dfdca10..94d6874 100644 --- a/lib/Internal/EmailRecipient.php +++ b/lib/Internal/EmailRecipient.php @@ -5,8 +5,6 @@ use PostHog\EmailError; /** - * Checks who an email goes to: its address, distinct ID and idempotency key. - * * @internal */ final class EmailRecipient diff --git a/lib/Internal/EmailReplies.php b/lib/Internal/EmailReplies.php index 7fb7897..9f9f901 100644 --- a/lib/Internal/EmailReplies.php +++ b/lib/Internal/EmailReplies.php @@ -9,8 +9,6 @@ use Symfony\Component\Clock\Clock; /** - * Reads PostHog's answers to email requests. - * * @internal */ final class EmailReplies From 8b0551a89dc1103da80a10ffe86f2d323fcc5a34 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:07:43 +0100 Subject: [PATCH 08/44] fix(emails): keep batch results when a read by key throws, set later errors on every retry A read by key at the end of a batch is best effort: any Throwable from it, such as an ErrorException from a promoted deprecation or an Error from a missing class, now stops the reads, and batch() still returns its result or throws its EmailBatchError with every recipient. An attempt that can't confirm a request, a 503, a lost answer or an answer without a result per recipient, now sets the later error of each recipient an earlier attempt already left unconfirmed. The first such attempt still leaves it null. Shared content over 4 MiB names its largest field, such as from or reply_to, not only html, text or subject. The memory test runs a batch of 10,000 recipients in a child process under a 26 MiB limit, and the shutdown test no longer asserts the fixture's own flag. Co-Authored-By: Claude Opus 5.5 --- lib/Emails.php | 4 +- lib/Internal/EmailBatch.php | 42 ++++------- test/EmailsBatchTest.php | 134 ++++++++++++++++++++++++++++++++---- 3 files changed, 136 insertions(+), 44 deletions(-) diff --git a/lib/Emails.php b/lib/Emails.php index 75aac6c..42f5c31 100644 --- a/lib/Emails.php +++ b/lib/Emails.php @@ -1150,7 +1150,7 @@ private function sendBatch(EmailBatch $run, string $appHost, string $secretKey, $reply = $this->request('POST', $url, $headers, $body, $timeoutMs); } catch (EmailError $error) { if (in_array($error->getErrorCode(), self::LOST_ANSWER_CODES, true)) { - $run->lost($position); + $run->lost($position, $error); } throw $error; } @@ -1184,6 +1184,8 @@ private function readUnconfirmed(EmailBatch $run, string $appHost, string $secre continue; } return; + } catch (Throwable) { + return; } $run->found($index, $status->getId()); } diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index 6928d50..9f3b843 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -195,26 +195,13 @@ public function requestBody(int $position): string return $this->opening . implode(',', $wires) . ']}'; } - /** - * @param EmailError|null $laterError What the attempt answered, kept as the later error of a recipient an - * earlier attempt already left `unconfirmed`. - */ - public function lost(int $position, ?EmailError $laterError = null): void + public function lost(int $position, EmailError $error): void { + $this->recordLaterError($position, $error); foreach ($this->requests[$position] as $index) { - $earlier = $this->results[$index] ?? null; - if ($laterError !== null && $this->isUnconfirmed($index)) { - $this->set( - $index, - 'unconfirmed', - $earlier->getMessageId(), - error: $earlier->getError(), - laterError: $laterError - ); - continue; + if (!$this->isUnconfirmed($index)) { + $this->set($index, 'unconfirmed', error: self::unconfirmed(null)); } - $messageId = $earlier?->getMessageId(); - $this->set($index, 'unconfirmed', $messageId, error: self::unconfirmed($messageId)); } } @@ -227,23 +214,22 @@ public function answer(int $position, int $status, string $body, array $headers) $fields = EmailReplies::fields($body); if ($status < 200 || $status >= 300) { $error = self::requestError($fields, $status, $headers, $indices); - if ($status >= 500) { - $this->lost($position); - } elseif ($error->getErrorCode() === self::IN_FLIGHT) { + if ($status >= 500 || $error->getErrorCode() === self::IN_FLIGHT) { $this->lost($position, $error); } else { - $this->refusedLater($position, $error); + $this->recordLaterError($position, $error); } throw $error; } $slots = $fields['results'] ?? null; if (!is_array($slots) || !array_is_list($slots) || count($slots) !== count($indices)) { - $this->lost($position); - throw new EmailError( + $error = new EmailError( 'api_error', 'PostHog answered the batch without a result for each recipient.', $status ); + $this->lost($position, $error); + throw $error; } foreach ($indices as $slot => $index) { $this->settle($index, is_array($slots[$slot]) ? $slots[$slot] : []); @@ -255,7 +241,7 @@ public function answer(int $position, int $status, string $body, array $headers) } } - private function refusedLater(int $position, EmailError $error): void + private function recordLaterError(int $position, EmailError $error): void { foreach ($this->requests[$position] as $index) { if ($this->isUnconfirmed($index)) { @@ -483,13 +469,11 @@ private static function unconfirmed(?string $messageId): EmailError private static function sharedTooLarge(array $shared): EmailError { $sizes = []; - foreach (['html', 'text', 'subject'] as $field) { - if (is_string($shared[$field] ?? null)) { - $sizes[$field] = strlen($shared[$field]); - } + foreach (array_diff_key($shared, ['template_id' => true, 'template_key' => true]) as $name => $value) { + $sizes[$name === 'message_data' ? 'template_data' : $name] = strlen(self::encode([$value], $name)); } arsort($sizes); - $field = array_key_exists('template_id', $shared) ? 'template_data' : (string) array_key_first($sizes); + $field = (string) array_key_first($sizes); return new EmailError( 'content_too_large', diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index 851fcfd..313481e 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -3,6 +3,8 @@ namespace PostHog\Test; use Closure; +use Error; +use ErrorException; use DateTimeImmutable; use DateTimeZone; use PHPUnit\Framework\Attributes\DataProvider; @@ -13,6 +15,7 @@ use PostHog\Emails; use PostHog\SendBatchResult; use stdClass; +use Throwable; use Symfony\Component\Clock\Clock; use Symfony\Component\Clock\ClockInterface; use Symfony\Component\Clock\MockClock; @@ -506,6 +509,11 @@ public static function sharedContentOver4Mib(): array return [ 'html' => [['template_key' => 'news', 'subject' => 'News', 'html' => $over, 'text' => 'Hi'], 'html'], 'text' => [['template_key' => 'news', 'subject' => 'News', 'html' => '

Hi

', 'text' => $over], 'text'], + 'from' => [['template_key' => 'news', 'subject' => 'News', 'html' => '

Hi

', 'from' => $over], 'from'], + 'reply_to' => [ + ['template_key' => 'news', 'subject' => 'News', 'html' => '

Hi

', 'reply_to' => $over], + 'reply_to', + ], 'template_data' => [ ['template_id' => self::TEMPLATE_ID, 'template_data' => ['note' => $over]], 'template_data', @@ -527,21 +535,48 @@ public function testSharedContentOver4MibIsRefusedBeforeAnyRequest(array $conten $this->assertSame([], $this->requests); } - public function testHoldsOneRequestBodyAtATime(): void + public function testABatchOf10000RecipientsFitsIn26MibOfMemory(): void { - $recipients = self::recipients(3000); - $usageAtTheFirstRequest = 0; - $this->reply(function (string $url, string $body) use (&$usageAtTheFirstRequest): array { - $usageAtTheFirstRequest = memory_get_usage(); - - return self::allQueued()($url, $body); - }, ...array_fill(0, 29, self::allQueued())); - $usageBefore = memory_get_usage(); - - $this->batch($recipients, ['template_data' => ['note' => str_repeat('x', 200_000)]]); + $script = tempnam(sys_get_temp_dir(), 'posthog-emails-batch-'); + file_put_contents($script, <<<'PHP' + 'msg_' . $recipient['idempotency_key'], 'status' => 'queued']; + } + + return [200, json_encode(['results' => $slots]), []]; +}); +$recipients = []; +for ($index = 0; $index < 10000; $index++) { + $recipients[] = ['to' => "user$index@example.com", 'idempotency_key' => "key-$index"]; +} +$result = $emails->batch([ + 'recipients' => $recipients, + 'template_id' => '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b', + 'template_data' => ['note' => str_repeat('x', 200000)], +]); +$queued = count(array_filter($result->getResults(), static fn($email): bool => $email->getStatus() === 'queued')); +echo json_encode([$requests, $queued]); +PHP); + try { + $command = escapeshellarg(PHP_BINARY) . ' -d memory_limit=26M ' . escapeshellarg($script) . ' ' + . escapeshellarg(__DIR__ . '/../vendor/autoload.php') . ' 2>&1'; + exec($command, $output, $exitCode); - $this->assertSame(array_fill(0, 30, 100), $this->recipientsPerRequest()); - $this->assertLessThan(5_000_000, $usageAtTheFirstRequest - $usageBefore); + $this->assertSame([0, '[100,10000]'], [$exitCode, implode("\n", $output)]); + } finally { + unlink($script); + } } public static function requestsAtTheLimit(): array @@ -749,7 +784,6 @@ public function testAShutdownDuringARetryWaitSendsNoRetry(): void $this->assertSame('client_closed', $error->getErrorCode()); $this->assertCount(1, $this->requests); - $this->assertTrue($this->closed); $this->assertSame( [...self::times(100, 'failed'), ...self::times(50, 'not_attempted')], self::statuses($error->getResults()) @@ -941,6 +975,78 @@ public function testA404SaysBatchSendsAreUnavailable(string $body, string $messa $this->assertSame('Check template_id, or ' . self::SEND_SINGLY, $error->getFix()); } + public static function retriesAfterAnUnconfirmingAttempt(): array + { + $unavailable = self::wholeCall(503, 'delivery_unavailable'); + + return [ + 'a 503, then an answer without a result per recipient' => [$unavailable, self::ok(), 'api_error'], + 'a lost answer, then an answer without a result per recipient' => [ + self::networkError(), + self::ok(), + 'api_error', + ], + 'a 503, then a 503' => [$unavailable, $unavailable, 'delivery_unavailable'], + ]; + } + + #[DataProvider('retriesAfterAnUnconfirmingAttempt')] + public function testARetryThatCannotConfirmEitherIsTheLaterError( + mixed $first, + mixed $retry, + string $laterCode + ): void { + $this->reply($first, $retry, self::wholeCall(404, 'not_found')); + + $error = $this->batchError(self::recipients(1), ['max_retries' => 1]); + + [$result] = $error->getResults(); + $this->assertSame('unconfirmed', $result->getStatus()); + $this->assertSame('delivery_unavailable', $result->getError()->getErrorCode()); + $this->assertSame($laterCode, $result->getLaterError()?->getErrorCode()); + } + + public static function lookupFailures(): array + { + return [ + 'a promoted deprecation' => [new ErrorException('Constant DATE_RFC7231 is deprecated', 0, E_DEPRECATED)], + 'a missing class' => [new Error('Class "Symfony\\Component\\Clock\\Clock" not found')], + ]; + } + + #[DataProvider('lookupFailures')] + public function testALookupThatThrowsStopsTheReadsAndKeepsEveryResult(Throwable $failure): void + { + $this->reply( + self::ok(self::queued('m0'), self::notConfirmed(null), self::notConfirmed(null)), + static function () use ($failure): never { + throw $failure; + } + ); + + $result = $this->batch(self::recipients(3), ['max_retries' => 0]); + + $this->assertSame(['key-1'], $this->readsByKey()); + $this->assertSame( + [['queued', 'm0'], ['unconfirmed', null], ['unconfirmed', null]], + array_map(static fn($r): array => [$r->getStatus(), $r->getMessageId()], $result->getResults()) + ); + } + + #[DataProvider('lookupFailures')] + public function testALookupThatThrowsAfterAFailedRequestStillThrowsTheBatchError(Throwable $failure): void + { + $this->reply(self::networkError(), static function () use ($failure): never { + throw $failure; + }); + + $error = $this->batchError(self::recipients(2), ['max_retries' => 0]); + + $this->assertSame('network_error', $error->getErrorCode()); + $this->assertSame(['key-0'], $this->readsByKey()); + $this->assertSame(['unconfirmed', 'unconfirmed'], self::statuses($error->getResults())); + } + public function testAnAnswerWithoutAResultPerRecipientLeavesTheRequestUnconfirmed(): void { $notFound = self::wholeCall(404, 'not_found'); From ccad352d931e27ece809014a6a5aa99d16df6694 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:07:43 +0100 Subject: [PATCH 09/44] docs(emails): build batch keys from a stored ID, call the reads by key best effort The README and the batch() docblock build each idempotency key from an ID stored with the job, such as the digest's own ID, so a retry after midnight makes the same keys. They say the end-of-batch reads by key stop at the first failure other than a 404. Co-Authored-By: Claude Opus 5.5 --- README.md | 10 +++++----- lib/Emails.php | 21 +++++++++++++-------- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 70a0456..cf1ac00 100644 --- a/README.md +++ b/README.md @@ -89,13 +89,13 @@ $status = PostHog::emails()->get($result->getId()); // queued, sent, delivered, `batch()` sends the same email to many recipients, one email each, and returns a result per recipient in the order of `recipients`: ```php -$run = 'digest:' . date('Y-m-d'); // one key per email of this run +// $digestId is stored with the job, so a retry of the job makes the same keys $result = PostHog::emails()->batch([ 'template_id' => '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b', 'template_data' => ['team' => 'Analytics'], // shared by every recipient 'recipients' => [ - ['to' => 'ada@example.com', 'template_data' => ['name' => 'Ada'], 'idempotency_key' => "$run:ada"], - ['to' => 'alan@example.com', 'template_data' => ['name' => 'Alan'], 'idempotency_key' => "$run:alan"], + ['to' => 'ada@example.com', 'template_data' => ['name' => 'Ada'], 'idempotency_key' => "$digestId:ada"], + ['to' => 'alan@example.com', 'template_data' => ['name' => 'Alan'], 'idempotency_key' => "$digestId:alan"], ], ]); foreach ($result->getResults() as $email) { @@ -107,8 +107,8 @@ foreach ($result->getResults() as $email) { - **Recipients.** Each recipient has `to` and optional `distinct_id`, `idempotency_key` and `template_data`. A recipient's `template_data` is merged over the shared `template_data`, and its keys replace the shared ones. With `template_key`, the content is the same for every recipient, so a recipient can't carry `template_data`. A batch takes no `cc`, `bcc`, `attachments` or `scheduled_at`: send those emails with `send()`. - **Requests.** The client sends at most 100 recipients and 4 MiB of JSON per request, one request after another, and waits at least 45 seconds for each answer. Shared content over 4 MiB throws `content_too_large` before any request. A recipient whose email alone is over 4 MiB is `failed` with `content_too_large`. -- **Idempotency keys.** Every retry reuses each recipient's key, so a retry never queues an email twice. Without a key, the client makes one that covers its own retries but not a second call. When a batch may be cut off and run again, pass keys you store: send it again with the same key within 24 hours, so it goes out once. Each recipient of a call needs a different key. Make each key name one email of one run, such as `digest:2026-11-24:ada`. Never reuse a key for another email: PostHog would replay the earlier email instead of sending this one. -- **Statuses.** `getStatus()` is `queued` when PostHog accepted the email, `failed` when it refused it (`getError()` says why, such as a suppressed address), `unconfirmed` when the client can't tell, such as after a lost answer, and `not_attempted` when an earlier request of the batch failed. At the end of every batch, the client reads each `unconfirmed` email without a message ID by its key. When PostHog has the email, the recipient comes back still `unconfirmed`, with its `getMessageId()`. Send each `unconfirmed` email again with the same key within 24 hours, so it goes out once. `getWarnings()` holds PostHog's warnings, each once. +- **Idempotency keys.** Every retry reuses each recipient's key, so a retry never queues an email twice. Without a key, the client makes one that covers its own retries but not a second call. When a batch may be cut off and run again, pass keys you store: send it again with the same key within 24 hours, so it goes out once. Each recipient of a call needs a different key. Build each key from an ID you store with the job, such as the digest's own ID, never from the time of the run: a retry after midnight would make new keys and send the emails again. Never reuse a key for another email: PostHog would replay the earlier email instead of sending this one. +- **Statuses.** `getStatus()` is `queued` when PostHog accepted the email, `failed` when it refused it (`getError()` says why, such as a suppressed address), `unconfirmed` when the client can't tell, such as after a lost answer, and `not_attempted` when an earlier request of the batch failed. At the end of every batch, the client tries to read each `unconfirmed` email without a message ID by its key. It stops at the first read that fails other than with a 404, so the rest keep no message ID. When PostHog has the email, the recipient comes back still `unconfirmed`, with its `getMessageId()`. Send each `unconfirmed` email again with the same key within 24 hours, so it goes out once. `getWarnings()` holds PostHog's warnings, each once. - **Errors.** A request that fails as a whole, such as a rate limit past its retries, stops the batch and throws `PostHog\EmailBatchError`, whose `getResults()` holds every recipient. `batch_unavailable` (409) means the project can't send batches yet, and is never retried. `not_found` (404) means the template doesn't exist or batch sends are off. For both, send each email the batch didn't queue with `send()` and its recipient's `idempotency_key`. ## Questions? diff --git a/lib/Emails.php b/lib/Emails.php index 42f5c31..8be30b9 100644 --- a/lib/Emails.php +++ b/lib/Emails.php @@ -419,8 +419,9 @@ public function get(string $messageId): EmailStatus * Each recipient's `idempotency_key` is 1 to 255 visible ASCII characters, a different one for each recipient * of the call, and every retry reuses it, so a retry never queues an email twice. 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. Make - * each key name one email of one run, such as `digest:2026-11-24:ada`. A single send and a batch recipient + * and run again: a rerun within 24 hours replays the emails that went out instead of sending them twice. Build + * each key from an ID you store with the job, such as the digest's own ID, never from the time of the run, so + * a retry after midnight makes the same keys. 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 would * replay the earlier email instead of sending this one. * @@ -433,21 +434,25 @@ public function get(string $messageId): EmailStatus * - `not_attempted`: an earlier request of the batch failed, so the client sent nothing for it. * * A request that fails as a whole, such as a rate limit past its retries, stops the batch and throws - * EmailBatchError, whose getResults() holds every recipient. At the end of every batch, the client reads each - * `unconfirmed` email without a message ID by its key. When PostHog has the email, the recipient comes back - * still `unconfirmed`, with the email's getMessageId(). The code `batch_unavailable` (409) means the project + * EmailBatchError, whose getResults() holds every recipient. At the end of every batch, the client tries to read + * each `unconfirmed` email without a message ID by its key. It stops at the first read that fails other than + * with a 404, so the rest keep no message ID. When PostHog has the email, the recipient comes back still + * `unconfirmed`, with the email's getMessageId(). The code `batch_unavailable` (409) means the project * can't send batches yet, and is never retried. `not_found` (404) means the template doesn't exist or batch * sends are off for the project. For both, send each email the batch didn't queue with send() and its * recipient's `idempotency_key`. Shared content over 4 MiB of JSON throws `content_too_large` before any * request, and a recipient whose email alone is that large is `failed` with `content_too_large`. * * ```php - * $run = 'digest:' . date('Y-m-d'); * $result = $client->emails()->batch([ * 'template_id' => '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b', * 'recipients' => [ - * ['to' => 'ada@example.com', 'template_data' => ['name' => 'Ada'], 'idempotency_key' => "$run:ada"], - * ['to' => 'alan@example.com', 'template_data' => ['name' => 'Alan'], 'idempotency_key' => "$run:alan"], + * ['to' => 'ada@example.com', 'template_data' => ['name' => 'Ada'], 'idempotency_key' => "$digestId:ada"], + * [ + * 'to' => 'alan@example.com', + * 'template_data' => ['name' => 'Alan'], + * 'idempotency_key' => "$digestId:alan", + * ], * ], * ]); * foreach ($result->getResults() as $email) { From 41a3acdeaa62b4e07b2662c1b92bd0bfe29a4a96 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:15:01 +0100 Subject: [PATCH 10/44] fix(emails): diagnose oversized batch content from its only encoding The batch now encodes each shared field once and builds the request body's opening from those pieces, so content_too_large names the largest field from the same encoding. A JsonSerializable value is never serialized a second time, so one that answers differently, or throws, on a second call can no longer turn content_too_large into invalid_form or another exception. Co-Authored-By: Claude Opus 5.5 --- lib/Internal/EmailBatch.php | 27 ++++++++++++++++++-------- test/EmailsBatchTest.php | 38 +++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 8 deletions(-) diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index 9f3b843..82166a5 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -53,9 +53,17 @@ public static function prepare(array $shared, mixed $recipients): self field: 'recipients' ); } - $emptyBody = self::encode([...$shared, 'recipients' => []], 'The email'); - if (strlen($emptyBody) > self::MAX_REQUEST_BYTES) { - throw self::sharedTooLarge($shared); + $encoded = []; + foreach ($shared as $name => $value) { + $encoded[$name] = self::encode($value, 'The email'); + } + $pairs = []; + foreach ($encoded as $name => $json) { + $pairs[] = self::encode((string) $name, 'The email') . ':' . $json; + } + $opening = '{' . implode(',', [...$pairs, '"recipients":[']); + if (strlen($opening) + strlen(']}') > self::MAX_REQUEST_BYTES) { + throw self::sharedTooLarge($encoded); } $isTemplateForm = array_key_exists('template_id', $shared); $members = []; @@ -75,7 +83,7 @@ public static function prepare(array $shared, mixed $recipients): self $members[] = $member; } - return new self($members, substr($emptyBody, 0, -strlen(']}'))); + return new self($members, $opening); } /** @@ -145,7 +153,7 @@ private static function templateData(int $index, mixed $data, bool $isTemplateFo return $data === [] ? (object) [] : $data; } - private static function encode(array $payload, string $what): string + private static function encode(mixed $payload, string $what): string { try { return json_encode($payload, self::JSON_FLAGS); @@ -466,11 +474,14 @@ private static function unconfirmed(?string $messageId): EmailError /** * @param array $shared */ - private static function sharedTooLarge(array $shared): EmailError + /** + * @param array $encoded + */ + private static function sharedTooLarge(array $encoded): EmailError { $sizes = []; - foreach (array_diff_key($shared, ['template_id' => true, 'template_key' => true]) as $name => $value) { - $sizes[$name === 'message_data' ? 'template_data' : $name] = strlen(self::encode([$value], $name)); + foreach (array_diff_key($encoded, ['template_id' => true, 'template_key' => true]) as $name => $json) { + $sizes[$name === 'message_data' ? 'template_data' : $name] = strlen($json); } arsort($sizes); $field = (string) array_key_first($sizes); diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index 313481e..bf43d76 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -16,6 +16,8 @@ use PostHog\SendBatchResult; use stdClass; use Throwable; +use JsonSerializable; +use RuntimeException; use Symfony\Component\Clock\Clock; use Symfony\Component\Clock\ClockInterface; use Symfony\Component\Clock\MockClock; @@ -535,6 +537,42 @@ public function testSharedContentOver4MibIsRefusedBeforeAnyRequest(array $conten $this->assertSame([], $this->requests); } + public static function valuesThatChangeOnASecondEncoding(): array + { + return [ + 'INF the second time' => [static fn(): float => INF], + 'an exception the second time' => [static function (): never { + throw new RuntimeException('Serialized twice.'); + }], + ]; + } + + #[DataProvider('valuesThatChangeOnASecondEncoding')] + public function testSharedContentOver4MibIsDiagnosedFromItsOnlyEncoding(Closure $secondTime): void + { + $note = new class (str_repeat('x', self::FOUR_MIB), $secondTime) implements JsonSerializable { + private int $encodings = 0; + + public function __construct(private string $first, private Closure $secondTime) + { + } + + public function jsonSerialize(): mixed + { + return $this->encodings++ === 0 ? $this->first : ($this->secondTime)(); + } + }; + + $error = $this->refusal([ + 'recipients' => self::recipients(1), + 'template_id' => self::TEMPLATE_ID, + 'template_data' => ['note' => $note], + ]); + + $this->assertSame(['content_too_large', 'template_data'], [$error->getErrorCode(), $error->getField()]); + $this->assertSame([], $this->requests); + } + public function testABatchOf10000RecipientsFitsIn26MibOfMemory(): void { $script = tempnam(sys_get_temp_dir(), 'posthog-emails-batch-'); From 63060725eba8236593471d29479e3fafcfc7e68d Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:15:01 +0100 Subject: [PATCH 11/44] test(emails): cover a retry that loses its answer again, size the memory test to what PostHog takes A retry that loses its answer at the transport keeps the recipient unconfirmed with its first error, and records network_error as its later error. The memory test shares 150,000 bytes of template_data, which PostHog accepts for 100 recipients, under a 24 MiB limit that the batch before it built one body at a time still exhausts. Co-Authored-By: Claude Opus 5.5 --- test/EmailsBatchTest.php | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index bf43d76..06a43d0 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -573,7 +573,7 @@ public function jsonSerialize(): mixed $this->assertSame([], $this->requests); } - public function testABatchOf10000RecipientsFitsIn26MibOfMemory(): void + public function testABatchOf10000RecipientsFitsIn24MibOfMemory(): void { $script = tempnam(sys_get_temp_dir(), 'posthog-emails-batch-'); file_put_contents($script, <<<'PHP' @@ -601,13 +601,13 @@ public function testABatchOf10000RecipientsFitsIn26MibOfMemory(): void $result = $emails->batch([ 'recipients' => $recipients, 'template_id' => '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b', - 'template_data' => ['note' => str_repeat('x', 200000)], + 'template_data' => ['note' => str_repeat('x', 150000)], ]); $queued = count(array_filter($result->getResults(), static fn($email): bool => $email->getStatus() === 'queued')); echo json_encode([$requests, $queued]); PHP); try { - $command = escapeshellarg(PHP_BINARY) . ' -d memory_limit=26M ' . escapeshellarg($script) . ' ' + $command = escapeshellarg(PHP_BINARY) . ' -d memory_limit=24M ' . escapeshellarg($script) . ' ' . escapeshellarg(__DIR__ . '/../vendor/autoload.php') . ' 2>&1'; exec($command, $output, $exitCode); @@ -1028,6 +1028,19 @@ public static function retriesAfterAnUnconfirmingAttempt(): array ]; } + public function testARetryThatLosesItsAnswerAgainIsTheLaterError(): void + { + $this->reply(self::networkError(), self::networkError(), self::wholeCall(404, 'not_found')); + + $error = $this->batchError(self::recipients(1), ['max_retries' => 1]); + + $this->assertSame('network_error', $error->getErrorCode()); + [$result] = $error->getResults(); + $this->assertSame([2, 'unconfirmed'], [count($this->batchBodies()), $result->getStatus()]); + $this->assertSame('delivery_unavailable', $result->getError()->getErrorCode()); + $this->assertSame('network_error', $result->getLaterError()?->getErrorCode()); + } + #[DataProvider('retriesAfterAnUnconfirmingAttempt')] public function testARetryThatCannotConfirmEitherIsTheLaterError( mixed $first, From b1dc21fd9c256d74b1520ba2527c3803c543b401 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:21:31 +0100 Subject: [PATCH 12/44] fix(emails): size shared batch content before building the request Co-Authored-By: Claude Opus 5.5 --- lib/Internal/EmailBatch.php | 11 +++++------ test/EmailsBatchTest.php | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index 82166a5..d928215 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -54,17 +54,19 @@ public static function prepare(array $shared, mixed $recipients): self ); } $encoded = []; + $size = strlen('{"recipients":[]}'); foreach ($shared as $name => $value) { $encoded[$name] = self::encode($value, 'The email'); + $size += strlen(self::encode((string) $name, 'The email')) + strlen($encoded[$name]) + strlen(':,'); + } + if ($size > self::MAX_REQUEST_BYTES) { + throw self::sharedTooLarge($encoded); } $pairs = []; foreach ($encoded as $name => $json) { $pairs[] = self::encode((string) $name, 'The email') . ':' . $json; } $opening = '{' . implode(',', [...$pairs, '"recipients":[']); - if (strlen($opening) + strlen(']}') > self::MAX_REQUEST_BYTES) { - throw self::sharedTooLarge($encoded); - } $isTemplateForm = array_key_exists('template_id', $shared); $members = []; $firstWithKey = []; @@ -471,9 +473,6 @@ private static function unconfirmed(?string $messageId): EmailError ); } - /** - * @param array $shared - */ /** * @param array $encoded */ diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index 06a43d0..50a1a11 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -617,6 +617,40 @@ public function testABatchOf10000RecipientsFitsIn24MibOfMemory(): void } } + public function testA32MibHtmlIsRefusedWithin128MibOfMemory(): void + { + $script = tempnam(sys_get_temp_dir(), 'posthog-emails-batch-'); + file_put_contents($script, <<<'PHP' +batch([ + 'recipients' => [['to' => 'user@example.com']], + 'template_key' => 'news', + 'subject' => 'News', + 'html' => str_repeat('x', 32 * 1024 * 1024), + ]); +} catch (PostHog\EmailError $error) { + echo json_encode([$requests, $error->getErrorCode(), $error->getField()]); +} +PHP); + try { + $command = escapeshellarg(PHP_BINARY) . ' -d memory_limit=128M ' . escapeshellarg($script) . ' ' + . escapeshellarg(__DIR__ . '/../vendor/autoload.php') . ' 2>&1'; + exec($command, $output, $exitCode); + + $this->assertSame([0, '[0,"content_too_large","html"]'], [$exitCode, implode("\n", $output)]); + } finally { + unlink($script); + } + } + public static function requestsAtTheLimit(): array { return [ From ab8f68ac2011f5c525a6933fe6258a746bea904b Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:27:03 +0100 Subject: [PATCH 13/44] test(emails): cover shared batch content at the 4 MiB request limit Co-Authored-By: Claude Opus 5.5 --- test/EmailsBatchTest.php | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index 50a1a11..550ce96 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -537,6 +537,31 @@ public function testSharedContentOver4MibIsRefusedBeforeAnyRequest(array $conten $this->assertSame([], $this->requests); } + public static function sharedContentAtTheLimit(): array + { + return [ + 'exactly 4 MiB' => [0, 'recipient fails with content_too_large'], + 'one byte more' => [1, 'batch throws content_too_large for template_data'], + ]; + } + + #[DataProvider('sharedContentAtTheLimit')] + public function testSharedContentTakesUpToExactly4MibOfRequest(int $bytesOver, string $outcome): void + { + $empty = ['template_id' => self::TEMPLATE_ID, 'message_data' => ['n' => ''], 'recipients' => []]; + $note = str_repeat('a', self::FOUR_MIB - strlen(json_encode($empty)) + $bytesOver); + + try { + $result = $this->batch(self::recipients(1), ['template_data' => ['n' => $note]]); + $error = $result->getResults()[0]->getError(); + $actual = "recipient fails with {$error->getErrorCode()}"; + } catch (EmailError $error) { + $actual = "batch throws {$error->getErrorCode()} for {$error->getField()}"; + } + + $this->assertSame([$outcome, []], [$actual, $this->requests]); + } + public static function valuesThatChangeOnASecondEncoding(): array { return [ From e1febea2d4c7c60c7f8bdc0b62a761fc1e9fe784 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:29:16 +0100 Subject: [PATCH 14/44] test(emails): assert the failed status at the shared content limit Co-Authored-By: Claude Opus 5.5 --- test/EmailsBatchTest.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index 550ce96..c72af32 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -540,7 +540,7 @@ public function testSharedContentOver4MibIsRefusedBeforeAnyRequest(array $conten public static function sharedContentAtTheLimit(): array { return [ - 'exactly 4 MiB' => [0, 'recipient fails with content_too_large'], + 'exactly 4 MiB' => [0, 'recipient failed with content_too_large'], 'one byte more' => [1, 'batch throws content_too_large for template_data'], ]; } @@ -553,8 +553,8 @@ public function testSharedContentTakesUpToExactly4MibOfRequest(int $bytesOver, s try { $result = $this->batch(self::recipients(1), ['template_data' => ['n' => $note]]); - $error = $result->getResults()[0]->getError(); - $actual = "recipient fails with {$error->getErrorCode()}"; + $recipient = $result->getResults()[0]; + $actual = "recipient {$recipient->getStatus()} with {$recipient->getError()->getErrorCode()}"; } catch (EmailError $error) { $actual = "batch throws {$error->getErrorCode()} for {$error->getField()}"; } From 691dc680d3ce9374c11431351e52ac552eec6527 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:59:12 +0100 Subject: [PATCH 15/44] fix(emails): name the right field when batch content is too large Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- lib/Emails.php | 4 ++-- lib/Internal/EmailBatch.php | 13 ++++++---- test/EmailsBatchTest.php | 48 +++++++++++++++++++++++++++++++++++++ 4 files changed, 60 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index cf1ac00..1ce001d 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ foreach ($result->getResults() as $email) { - **Recipients.** Each recipient has `to` and optional `distinct_id`, `idempotency_key` and `template_data`. A recipient's `template_data` is merged over the shared `template_data`, and its keys replace the shared ones. With `template_key`, the content is the same for every recipient, so a recipient can't carry `template_data`. A batch takes no `cc`, `bcc`, `attachments` or `scheduled_at`: send those emails with `send()`. - **Requests.** The client sends at most 100 recipients and 4 MiB of JSON per request, one request after another, and waits at least 45 seconds for each answer. Shared content over 4 MiB throws `content_too_large` before any request. A recipient whose email alone is over 4 MiB is `failed` with `content_too_large`. -- **Idempotency keys.** Every retry reuses each recipient's key, so a retry never queues an email twice. Without a key, the client makes one that covers its own retries but not a second call. When a batch may be cut off and run again, pass keys you store: send it again with the same key within 24 hours, so it goes out once. Each recipient of a call needs a different key. Build each key from an ID you store with the job, such as the digest's own ID, never from the time of the run: a retry after midnight would make new keys and send the emails again. Never reuse a key for another email: PostHog would replay the earlier email instead of sending this one. +- **Idempotency keys.** Every retry reuses each recipient's key, so a retry never queues an email twice. Without a key, the client makes one that covers its own retries but not a second call. When a batch may be cut off and run again, pass keys you store: send it again with the same key within 24 hours, so it goes out once. Each recipient of a call needs a different key. Build each key from an ID you store with the job, such as the digest's own ID, never from the time of the run: a retry after midnight would make new keys and send the emails again. Never reuse a key for another email: PostHog refuses it with `idempotency_key_reused`, and that email doesn't go out. - **Statuses.** `getStatus()` is `queued` when PostHog accepted the email, `failed` when it refused it (`getError()` says why, such as a suppressed address), `unconfirmed` when the client can't tell, such as after a lost answer, and `not_attempted` when an earlier request of the batch failed. At the end of every batch, the client tries to read each `unconfirmed` email without a message ID by its key. It stops at the first read that fails other than with a 404, so the rest keep no message ID. When PostHog has the email, the recipient comes back still `unconfirmed`, with its `getMessageId()`. Send each `unconfirmed` email again with the same key within 24 hours, so it goes out once. `getWarnings()` holds PostHog's warnings, each once. - **Errors.** A request that fails as a whole, such as a rate limit past its retries, stops the batch and throws `PostHog\EmailBatchError`, whose `getResults()` holds every recipient. `batch_unavailable` (409) means the project can't send batches yet, and is never retried. `not_found` (404) means the template doesn't exist or batch sends are off. For both, send each email the batch didn't queue with `send()` and its recipient's `idempotency_key`. diff --git a/lib/Emails.php b/lib/Emails.php index c1fc839..700a902 100644 --- a/lib/Emails.php +++ b/lib/Emails.php @@ -426,8 +426,8 @@ public function get(string $messageId): EmailStatus * and run again: a rerun within 24 hours replays the emails that went out instead of sending them twice. Build * each key from an ID you store with the job, such as the digest's own ID, never from the time of the run, so * a retry after midnight makes the same keys. 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 would - * replay the earlier email instead of sending this one. + * with the same key and the same email replay each other. Never reuse a key for another email: PostHog refuses + * it with `idempotency_key_reused`, and that email doesn't go out. * * Check each result's getStatus(): * diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index d928215..c7a54b7 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -118,16 +118,21 @@ private static function member(int $index, mixed $recipient, bool $isTemplateFor if ($distinctId !== null) { $wire['distinct_id'] = $distinctId; } - $field = "recipients__$index"; if (array_key_exists('template_data', $recipient)) { $wire['message_data'] = self::templateData($index, $recipient['template_data'], $isTemplateForm); + } + $encoded = self::encode($wire, "recipients[$index]"); + $field = "recipients__$index"; + if ($distinctId !== null && 2 * strlen(self::encode($distinctId, "recipients[$index]")) > strlen($encoded)) { + $field .= '__distinct_id'; + } elseif (array_key_exists('template_data', $recipient)) { $field .= '__template_data'; } return [ 'to' => $to, 'key' => $wire['idempotency_key'], - 'wire' => self::encode($wire, "recipients[$index]"), + 'wire' => $encoded, 'field' => $field, ]; } @@ -487,8 +492,8 @@ private static function sharedTooLarge(array $encoded): EmailError return new EmailError( 'content_too_large', - "The $field every recipient of the batch gets is larger than one batch request takes (4 MiB of JSON), " - . 'so no email was sent.', + 'The email every recipient of the batch gets is larger than one batch request takes (4 MiB of JSON), so ' + . "no email was sent. Its largest part is $field.", fix: "Make $field smaller, such as by linking to images instead of embedding them, or send each email " . 'with emails()->send().', field: $field diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index c72af32..25f580b 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -537,6 +537,54 @@ public function testSharedContentOver4MibIsRefusedBeforeAnyRequest(array $conten $this->assertSame([], $this->requests); } + public function testSharedContentOver4MibOnlyTogetherNamesItsLargestPart(): void + { + $half = intdiv(self::FOUR_MIB, 2) + 1024; + + $error = $this->refusal([ + 'recipients' => self::recipients(1), + 'template_key' => 'news', + 'subject' => 'News', + 'html' => str_repeat('h', $half + 1), + 'text' => str_repeat('t', $half), + ]); + + $this->assertSame([ + 'content_too_large', + 'html', + 'The email every recipient of the batch gets is larger than one batch request takes (4 MiB of JSON), so ' + . 'no email was sent. Its largest part is html.', + ], [$error->getErrorCode(), $error->getField(), $error->getMessage()]); + $this->assertSame([], $this->requests); + } + + public static function recipientsTooLargeAlone(): array + { + return [ + 'a large distinct_id' => [ + ['distinct_id' => str_repeat('d', self::FOUR_MIB), 'template_data' => ['greeting' => 'Hi']], + 'recipients__0__distinct_id', + ], + 'large template_data' => [ + ['distinct_id' => 'user-1', 'template_data' => ['note' => str_repeat('x', self::FOUR_MIB)]], + 'recipients__0__template_data', + ], + ]; + } + + #[DataProvider('recipientsTooLargeAlone')] + public function testARecipientTooLargeAloneNamesItsLargestField(array $fields, string $field): void + { + $result = $this->batch([['to' => 'a@example.com', 'idempotency_key' => 'k1', ...$fields]]); + + $recipient = $result->getResults()[0]; + $this->assertSame( + ['failed', 'content_too_large', $field], + [$recipient->getStatus(), $recipient->getError()->getErrorCode(), $recipient->getError()->getField()] + ); + $this->assertSame([], $this->requests); + } + public static function sharedContentAtTheLimit(): array { return [ From ec1b512fb61b3c2baa89ea41ef1e9d6a8b669112 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:10:44 +0100 Subject: [PATCH 16/44] fix(emails): size each recipient field once and name the largest Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- lib/Emails.php | 5 ++-- lib/Internal/EmailBatch.php | 40 ++++++++++++++++++++-------- test/EmailsBatchTest.php | 53 +++++++++++++++++++++++++++++-------- 4 files changed, 75 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 1ce001d..c25b5a3 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ foreach ($result->getResults() as $email) { - **Recipients.** Each recipient has `to` and optional `distinct_id`, `idempotency_key` and `template_data`. A recipient's `template_data` is merged over the shared `template_data`, and its keys replace the shared ones. With `template_key`, the content is the same for every recipient, so a recipient can't carry `template_data`. A batch takes no `cc`, `bcc`, `attachments` or `scheduled_at`: send those emails with `send()`. - **Requests.** The client sends at most 100 recipients and 4 MiB of JSON per request, one request after another, and waits at least 45 seconds for each answer. Shared content over 4 MiB throws `content_too_large` before any request. A recipient whose email alone is over 4 MiB is `failed` with `content_too_large`. -- **Idempotency keys.** Every retry reuses each recipient's key, so a retry never queues an email twice. Without a key, the client makes one that covers its own retries but not a second call. When a batch may be cut off and run again, pass keys you store: send it again with the same key within 24 hours, so it goes out once. Each recipient of a call needs a different key. Build each key from an ID you store with the job, such as the digest's own ID, never from the time of the run: a retry after midnight would make new keys and send the emails again. Never reuse a key for another email: PostHog refuses it with `idempotency_key_reused`, and that email doesn't go out. +- **Idempotency keys.** Every retry reuses each recipient's key, so a retry never queues an email twice. Without a key, the client makes one that covers its own retries but not a second call. When a batch may be cut off and run again, pass keys you store: send it again with the same key within 24 hours, so it goes out once. Each recipient of a call needs a different key. Build each key from an ID you store with the job, such as the digest's own ID, never from the time of the run: a retry after midnight would make new keys and send the emails again. Never reuse a key for another email: PostHog sends one email per key, so the other doesn't go out. PostHog usually refuses it with `idempotency_key_reused`, but two sends that arrive at the same time can both answer `queued`. - **Statuses.** `getStatus()` is `queued` when PostHog accepted the email, `failed` when it refused it (`getError()` says why, such as a suppressed address), `unconfirmed` when the client can't tell, such as after a lost answer, and `not_attempted` when an earlier request of the batch failed. At the end of every batch, the client tries to read each `unconfirmed` email without a message ID by its key. It stops at the first read that fails other than with a 404, so the rest keep no message ID. When PostHog has the email, the recipient comes back still `unconfirmed`, with its `getMessageId()`. Send each `unconfirmed` email again with the same key within 24 hours, so it goes out once. `getWarnings()` holds PostHog's warnings, each once. - **Errors.** A request that fails as a whole, such as a rate limit past its retries, stops the batch and throws `PostHog\EmailBatchError`, whose `getResults()` holds every recipient. `batch_unavailable` (409) means the project can't send batches yet, and is never retried. `not_found` (404) means the template doesn't exist or batch sends are off. For both, send each email the batch didn't queue with `send()` and its recipient's `idempotency_key`. diff --git a/lib/Emails.php b/lib/Emails.php index 700a902..0229b8d 100644 --- a/lib/Emails.php +++ b/lib/Emails.php @@ -426,8 +426,9 @@ public function get(string $messageId): EmailStatus * and run again: a rerun within 24 hours replays the emails that went out instead of sending them twice. Build * each key from an ID you store with the job, such as the digest's own ID, never from the time of the run, so * a retry after midnight makes the same keys. 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 - * it with `idempotency_key_reused`, and that email doesn't go out. + * with the same key and the same email replay each other. Never reuse a key for another email: PostHog sends one + * email per key, so the other doesn't go out. PostHog usually refuses it with `idempotency_key_reused`, but two + * sends that arrive at the same time can both answer `queued`. * * Check each result's getStatus(): * diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index c7a54b7..30ffd2e 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -32,7 +32,7 @@ final class EmailBatch private array $warnings = []; /** - * @param list $members + * @param list $members * @param string $opening The request body up to its first recipient. */ private function __construct(private array $members, private string $opening) @@ -89,7 +89,7 @@ public static function prepare(array $shared, mixed $recipients): self } /** - * @return array{to: string, key: string, wire: string, field: string} + * @return array{to: string, key: string, bytes: int, wire: ?string, field: string} */ private static function member(int $index, mixed $recipient, bool $isTemplateForm): array { @@ -121,22 +121,40 @@ private static function member(int $index, mixed $recipient, bool $isTemplateFor if (array_key_exists('template_data', $recipient)) { $wire['message_data'] = self::templateData($index, $recipient['template_data'], $isTemplateForm); } - $encoded = self::encode($wire, "recipients[$index]"); - $field = "recipients__$index"; - if ($distinctId !== null && 2 * strlen(self::encode($distinctId, "recipients[$index]")) > strlen($encoded)) { - $field .= '__distinct_id'; - } elseif (array_key_exists('template_data', $recipient)) { - $field .= '__template_data'; + $values = []; + $sizes = []; + $bytes = strlen('{}') + count($wire) - 1; + foreach ($wire as $name => $value) { + $values[$name] = self::encode($value, "recipients[$index]"); + $sizes[$name === 'message_data' ? 'template_data' : $name] = strlen($values[$name]); + $bytes += strlen("\"$name\":") + strlen($values[$name]); } + $named = array_intersect_key($sizes, ['distinct_id' => true, 'template_data' => true]); + arsort($named); + $largest = array_key_first($named); return [ 'to' => $to, 'key' => $wire['idempotency_key'], - 'wire' => $encoded, - 'field' => $field, + 'bytes' => $bytes, + 'wire' => $bytes > self::MAX_REQUEST_BYTES ? null : self::joined($values), + 'field' => $largest === null ? "recipients__$index" : "recipients__{$index}__$largest", ]; } + /** + * @param array $values + */ + private static function joined(array $values): string + { + $pairs = []; + foreach ($values as $name => $json) { + $pairs[] = "\"$name\":$json"; + } + + return '{' . implode(',', $pairs) . '}'; + } + private static function templateData(int $index, mixed $data, bool $isTemplateForm): array|object { $field = "recipients__{$index}__template_data"; @@ -179,7 +197,7 @@ private function split(): void $indices = []; $bytes = $emptyBytes; foreach ($this->members as $index => $member) { - $memberBytes = strlen($member['wire']); + $memberBytes = $member['bytes']; if ($emptyBytes + $memberBytes > self::MAX_REQUEST_BYTES) { $this->set($index, 'failed', error: self::recipientTooLarge($member['field'])); continue; diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index 25f580b..3f45fc7 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -561,21 +561,25 @@ public function testSharedContentOver4MibOnlyTogetherNamesItsLargestPart(): void public static function recipientsTooLargeAlone(): array { return [ - 'a large distinct_id' => [ - ['distinct_id' => str_repeat('d', self::FOUR_MIB), 'template_data' => ['greeting' => 'Hi']], - 'recipients__0__distinct_id', - ], - 'large template_data' => [ - ['distinct_id' => 'user-1', 'template_data' => ['note' => str_repeat('x', self::FOUR_MIB)]], - 'recipients__0__template_data', - ], + 'a large distinct_id' => [self::FOUR_MIB, 2, 'recipients__0__distinct_id'], + 'large template_data' => [6, self::FOUR_MIB, 'recipients__0__template_data'], + 'a distinct_id a little larger than template_data' => [2097130, 2097115, 'recipients__0__distinct_id'], + 'template_data a little larger than distinct_id' => [2097115, 2097130, 'recipients__0__template_data'], ]; } #[DataProvider('recipientsTooLargeAlone')] - public function testARecipientTooLargeAloneNamesItsLargestField(array $fields, string $field): void - { - $result = $this->batch([['to' => 'a@example.com', 'idempotency_key' => 'k1', ...$fields]]); + public function testARecipientTooLargeAloneNamesItsLargestField( + int $distinctIdBytes, + int $noteBytes, + string $field + ): void { + $result = $this->batch([[ + 'to' => 'a@example.com', + 'idempotency_key' => 'k1', + 'distinct_id' => str_repeat('d', $distinctIdBytes), + 'template_data' => ['x' => str_repeat('x', $noteBytes)], + ]]); $recipient = $result->getResults()[0]; $this->assertSame( @@ -690,6 +694,33 @@ public function testABatchOf10000RecipientsFitsIn24MibOfMemory(): void } } + public function testARecipientWithA10MibDistinctIdOfNulBytesFailsWithin128MibOfMemory(): void + { + $script = tempnam(sys_get_temp_dir(), 'posthog-emails-batch-'); + file_put_contents($script, <<<'PHP' + [500, '', []]); +$recipient = $emails->batch([ + 'recipients' => [['to' => 'user@example.com', 'distinct_id' => str_repeat("\0", 10 * 1024 * 1024)]], + 'template_id' => '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b', +])->getResults()[0]; +echo json_encode([$recipient->getStatus(), $recipient->getError()->getErrorCode(), $recipient->getError()->getField()]); +PHP); + try { + $command = escapeshellarg(PHP_BINARY) . ' -d memory_limit=128M ' . escapeshellarg($script) . ' ' + . escapeshellarg(__DIR__ . '/../vendor/autoload.php') . ' 2>&1'; + exec($command, $output, $exitCode); + + $this->assertSame( + [0, '["failed","content_too_large","recipients__0__distinct_id"]'], + [$exitCode, implode("\n", $output)] + ); + } finally { + unlink($script); + } + } + public function testA32MibHtmlIsRefusedWithin128MibOfMemory(): void { $script = tempnam(sys_get_temp_dir(), 'posthog-emails-batch-'); From 8bdde885f3301b05a582a91a8f2fa01f7ee8641f Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:14:32 +0100 Subject: [PATCH 17/44] fix(emails): stop reading unconfirmed batch emails back by key Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- lib/BatchEmailResult.php | 7 +- lib/Emails.php | 32 +----- lib/Internal/EmailBatch.php | 29 ----- test/EmailsBatchTest.php | 212 +++++++----------------------------- 5 files changed, 44 insertions(+), 238 deletions(-) diff --git a/README.md b/README.md index c25b5a3..2d2f2af 100644 --- a/README.md +++ b/README.md @@ -108,7 +108,7 @@ foreach ($result->getResults() as $email) { - **Recipients.** Each recipient has `to` and optional `distinct_id`, `idempotency_key` and `template_data`. A recipient's `template_data` is merged over the shared `template_data`, and its keys replace the shared ones. With `template_key`, the content is the same for every recipient, so a recipient can't carry `template_data`. A batch takes no `cc`, `bcc`, `attachments` or `scheduled_at`: send those emails with `send()`. - **Requests.** The client sends at most 100 recipients and 4 MiB of JSON per request, one request after another, and waits at least 45 seconds for each answer. Shared content over 4 MiB throws `content_too_large` before any request. A recipient whose email alone is over 4 MiB is `failed` with `content_too_large`. - **Idempotency keys.** Every retry reuses each recipient's key, so a retry never queues an email twice. Without a key, the client makes one that covers its own retries but not a second call. When a batch may be cut off and run again, pass keys you store: send it again with the same key within 24 hours, so it goes out once. Each recipient of a call needs a different key. Build each key from an ID you store with the job, such as the digest's own ID, never from the time of the run: a retry after midnight would make new keys and send the emails again. Never reuse a key for another email: PostHog sends one email per key, so the other doesn't go out. PostHog usually refuses it with `idempotency_key_reused`, but two sends that arrive at the same time can both answer `queued`. -- **Statuses.** `getStatus()` is `queued` when PostHog accepted the email, `failed` when it refused it (`getError()` says why, such as a suppressed address), `unconfirmed` when the client can't tell, such as after a lost answer, and `not_attempted` when an earlier request of the batch failed. At the end of every batch, the client tries to read each `unconfirmed` email without a message ID by its key. It stops at the first read that fails other than with a 404, so the rest keep no message ID. When PostHog has the email, the recipient comes back still `unconfirmed`, with its `getMessageId()`. Send each `unconfirmed` email again with the same key within 24 hours, so it goes out once. `getWarnings()` holds PostHog's warnings, each once. +- **Statuses.** `getStatus()` is `queued` when PostHog accepted the email, `failed` when it refused it (`getError()` says why, such as a suppressed address), `unconfirmed` when the client can't tell, such as after a lost answer, and `not_attempted` when an earlier request of the batch failed. Send each `unconfirmed` email again with the same key within 24 hours, so it goes out once. `getWarnings()` holds PostHog's warnings, each once. - **Errors.** A request that fails as a whole, such as a rate limit past its retries, stops the batch and throws `PostHog\EmailBatchError`, whose `getResults()` holds every recipient. `batch_unavailable` (409) means the project can't send batches yet, and is never retried. `not_found` (404) means the template doesn't exist or batch sends are off. For both, send each email the batch didn't queue with `send()` and its recipient's `idempotency_key`. ## Questions? diff --git a/lib/BatchEmailResult.php b/lib/BatchEmailResult.php index 96d8af5..498a28d 100644 --- a/lib/BatchEmailResult.php +++ b/lib/BatchEmailResult.php @@ -11,7 +11,7 @@ * - `failed`: PostHog didn't queue the email, and getError() says why, such as a suppressed address. * - `unconfirmed`: the client can't tell whether PostHog queued the email, such as after a lost answer. It may * still go out. Send it again with the same idempotency key within 24 hours, so it goes out once. - * getMessageId() is the email's ID when PostHog answered one or has an email under the key. + * getMessageId() is the email's ID when PostHog's answer named one. * getLaterError() holds what a later attempt in the same call answered, which describes only that attempt. * - `not_attempted`: an earlier request of the batch failed, so the client sent nothing for this recipient. */ @@ -66,9 +66,8 @@ public function getStatus(): string } /** - * The email's message ID when PostHog named it, also for some emails it didn't queue. For an `unconfirmed` - * email, it can be the ID of the email PostHog has under the recipient's key, which the client read at the end - * of the batch. Pass it to Emails::get() to read the email's status. + * The email's message ID when PostHog's answer named it, also for some emails it didn't queue. Pass it to + * Emails::get() to read the email's status. */ public function getMessageId(): ?string { diff --git a/lib/Emails.php b/lib/Emails.php index 0229b8d..0a8ae26 100644 --- a/lib/Emails.php +++ b/lib/Emails.php @@ -51,7 +51,6 @@ final class Emails private const UPLOADS_PATH = '/api/messaging/attachments/uploads/'; private const STATUS_PATH = '/api/messaging/emails/%s/'; private const BATCH_PATH = '/api/messaging/send/email_batch/'; - private const STATUS_BY_KEY_PATH = '/api/messaging/emails/status/'; private const US_APP_HOST = 'https://us.posthog.com'; private const EU_APP_HOST = 'https://eu.posthog.com'; private const CLOUD_APP_HOSTS = [ @@ -439,10 +438,7 @@ public function get(string $messageId): EmailStatus * - `not_attempted`: an earlier request of the batch failed, so the client sent nothing for it. * * A request that fails as a whole, such as a rate limit past its retries, stops the batch and throws - * EmailBatchError, whose getResults() holds every recipient. At the end of every batch, the client tries to read - * each `unconfirmed` email without a message ID by its key. It stops at the first read that fails other than - * with a 404, so the rest keep no message ID. When PostHog has the email, the recipient comes back still - * `unconfirmed`, with the email's getMessageId(). The code `batch_unavailable` (409) means the project + * EmailBatchError, whose getResults() holds every recipient. The code `batch_unavailable` (409) means the project * can't send batches yet, and is never retried. `not_found` (404) means the template doesn't exist or batch * sends are off for the project. For both, send each email the batch didn't queue with send() and its * recipient's `idempotency_key`. Shared content over 4 MiB of JSON throws `content_too_large` before any @@ -1170,35 +1166,9 @@ private function sendBatch(EmailBatch $run, string $appHost, string $secretKey, $this->withRetries($maxRetries, $attemptOnce, $closedBeforeARetry); } catch (EmailError $error) { $run->stop($position, $error); - $this->readUnconfirmed($run, $appHost, $secretKey); throw $run->failure($error); } } - $this->readUnconfirmed($run, $appHost, $secretKey); - } - - private function readUnconfirmed(EmailBatch $run, string $appHost, string $secretKey): void - { - $headers = $this->headers($secretKey, []); - foreach ($run->unconfirmedWithoutMessageId() as $index => $idempotencyKey) { - if (($this->isClosed)()) { - return; - } - $query = http_build_query(['idempotency_key' => $idempotencyKey], '', '&', PHP_QUERY_RFC3986); - try { - $status = self::parseStatusReply( - ...$this->request('GET', $appHost . self::STATUS_BY_KEY_PATH . '?' . $query, $headers, null) - ); - } catch (EmailError $error) { - if ($error->getStatusCode() === 404) { - continue; - } - return; - } catch (Throwable) { - return; - } - $run->found($index, $status->getId()); - } } /** diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index 30ffd2e..4492f94 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -346,35 +346,6 @@ private function skipFrom(int $position, EmailError $error): void } } - /** - * @return array The idempotency key of each `unconfirmed` recipient without a message ID, by its - * position in `recipients`. - */ - public function unconfirmedWithoutMessageId(): array - { - $keys = []; - foreach ($this->results as $index => $result) { - if ($result->getStatus() === 'unconfirmed' && $result->getMessageId() === null) { - $keys[$index] = $result->getIdempotencyKey(); - } - } - ksort($keys); - - return $keys; - } - - public function found(int $index, string $messageId): void - { - $result = $this->results[$index]; - $this->set( - $index, - 'unconfirmed', - $messageId, - error: $result->getError(), - laterError: $result->getLaterError() - ); - } - public function result(): SendBatchResult { return new SendBatchResult($this->outcome(), $this->warnings); diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index 3f45fc7..b9a95c1 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -3,8 +3,6 @@ namespace PostHog\Test; use Closure; -use Error; -use ErrorException; use DateTimeImmutable; use DateTimeZone; use PHPUnit\Framework\Attributes\DataProvider; @@ -15,7 +13,6 @@ use PostHog\Emails; use PostHog\SendBatchResult; use stdClass; -use Throwable; use JsonSerializable; use RuntimeException; use Symfony\Component\Clock\Clock; @@ -28,7 +25,6 @@ class EmailsBatchTest extends TestCase private const TEMPLATE_ID = '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b'; private const BATCH_URL = 'https://us.posthog.com/api/messaging/send/email_batch/'; - private const STATUS_BY_KEY_URL = 'https://us.posthog.com/api/messaging/emails/status/'; private const FOUR_MIB = 4 * 1024 * 1024; private const UUID_V4 = '/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/D'; private const WARNING_LOGGED = '[PostHog][Emails] Email warning sandbox_sender: Sent from the test sender.'; @@ -115,18 +111,6 @@ private static function wholeCall(int $status, ?string $code = null): array return [$status, $body, []]; } - /** @return array{int, string, list} */ - private static function statusFound(string $messageId, string $status = 'sent', ?string $reason = null): array - { - return [200, json_encode([ - 'id' => $messageId, - 'status' => $status, - 'created_at' => '2026-11-02T10:00:00Z', - 'status_at' => '2026-11-02T10:00:01Z', - 'reason' => $reason, - ]), []]; - } - /** @return array */ private static function notConfirmed(?string $messageId = 'm0'): array { @@ -215,18 +199,10 @@ private function recipientsPerRequest(): array return array_map(static fn(array $body): int => count($body['recipients']), $this->batchBodies()); } - /** @return list the idempotency keys of the emails read by key, in order */ - private function readsByKey(): array + /** @return list */ + private function requestUrls(): array { - $keys = []; - foreach ($this->requests as $request) { - if (str_starts_with($request['url'], self::STATUS_BY_KEY_URL)) { - parse_str((string) parse_url($request['url'], PHP_URL_QUERY), $query); - $keys[] = $query['idempotency_key']; - } - } - - return $keys; + return array_column($this->requests, 'url'); } /** @return list */ @@ -828,21 +804,19 @@ public function testARetryAfterALostAnswerKeepsARefusedRecipientUnconfirmed(): v public function testAnAnswerTooLargeToReadLeavesTheRequestUnconfirmed(): void { $this->reply( - new EmailError('response_too_large', 'PostHog answered with more than 1048576 bytes.'), - self::wholeCall(404, 'not_found') + new EmailError('response_too_large', 'PostHog answered with more than 1048576 bytes.') ); $error = $this->batchError(self::recipients(1)); $this->assertSame('response_too_large', $error->getErrorCode()); $this->assertSame(['unconfirmed'], self::statuses($error->getResults())); - $this->assertSame(['key-0'], $this->readsByKey()); + $this->assertSame([self::BATCH_URL], $this->requestUrls()); } public function testA503ThenARefusalOfTheWholeRequestKeepsTheRecipientUnconfirmed(): void { - $notFound = self::wholeCall(404, 'not_found'); - $this->reply(self::wholeCall(503, 'delivery_unavailable'), self::wholeCall(422, 'sending_paused'), $notFound); + $this->reply(self::wholeCall(503, 'delivery_unavailable'), self::wholeCall(422, 'sending_paused')); $error = $this->batchError(self::recipients(1)); @@ -865,39 +839,40 @@ public function testARecipientThePipelineDidNotConfirmIsUnconfirmed(): void $result->getError()->getStatusCode(), ]); $this->assertNull($result->getLaterError()); + $this->assertSame('key-0', $result->getIdempotencyKey()); } - public function testABatchThatSucceedsReadsEachUnconfirmedEmailWithoutAMessageId(): void + public function testABatchThatSucceedsReadsNothingBackForAnUnconfirmedEmail(): void { - $this->reply( - self::ok(self::queued('m0'), self::notConfirmed(null), self::notConfirmed('m2')), - self::statusFound('m1') - ); + $this->reply(self::ok(self::queued('m0'), self::notConfirmed(null), self::notConfirmed('m2'))); $result = $this->batch(self::recipients(3), ['max_retries' => 0]); - $this->assertSame(['key-1'], $this->readsByKey()); + $this->assertSame([self::BATCH_URL], $this->requestUrls()); $this->assertSame( - [['queued', 'm0'], ['unconfirmed', 'm1'], ['unconfirmed', 'm2']], - array_map(static fn($r): array => [$r->getStatus(), $r->getMessageId()], $result->getResults()) + [['queued', 'm0', 'key-0'], ['unconfirmed', null, 'key-1'], ['unconfirmed', 'm2', 'key-2']], + array_map( + static fn($r): array => [$r->getStatus(), $r->getMessageId(), $r->getIdempotencyKey()], + $result->getResults() + ) ); } public function testAWholeRequestInFlightAnswerLeavesItsRecipientsUnconfirmed(): void { - $this->reply(self::wholeCall(409, 'idempotency_key_in_flight'), self::statusFound('m0'), self::wholeCall(404)); + $this->reply(self::wholeCall(409, 'idempotency_key_in_flight')); $error = $this->batchError(self::recipients(2), ['max_retries' => 0]); $this->assertSame('idempotency_key_in_flight', $error->getErrorCode()); $this->assertSame( - [['unconfirmed', 'm0', null], ['unconfirmed', null, null]], + [['unconfirmed', null, null], ['unconfirmed', null, null]], array_map( static fn($r): array => [$r->getStatus(), $r->getMessageId(), $r->getLaterError()], $error->getResults() ) ); - $this->assertSame(['key-0', 'key-1'], $this->readsByKey()); + $this->assertSame([self::BATCH_URL], $this->requestUrls()); } public static function attemptsAfterAnInFlightAnswer(): array @@ -919,7 +894,7 @@ public function testTheAttemptAfterTheOneThatLeftARecipientUnconfirmedIsItsLater array $answers, string $laterCode ): void { - $this->reply(...$answers, ...[self::wholeCall(404)]); + $this->reply(...$answers); $error = $this->batchError(self::recipients(1), ['max_retries' => 1]); @@ -927,7 +902,7 @@ public function testTheAttemptAfterTheOneThatLeftARecipientUnconfirmedIsItsLater $this->assertSame('unconfirmed', $result->getStatus()); $this->assertSame('delivery_unavailable', $result->getError()->getErrorCode()); $this->assertSame($laterCode, $result->getLaterError()->getErrorCode()); - $this->assertCount(3, $this->requests); + $this->assertSame([self::BATCH_URL, self::BATCH_URL], $this->requestUrls()); } public function testAShutdownDuringABatchStopsItBeforeTheNextRequest(): void @@ -992,21 +967,6 @@ public function withTimeZone(DateTimeZone|string $timezone): static }; } - public function testAShutdownBeforeALostAnswerReadsNoEmailByItsKey(): void - { - $this->reply(function (): array { - $this->closed = true; - - return self::wholeCall(503, 'delivery_unavailable'); - }, self::statusFound('m0')); - - $error = $this->batchError(self::recipients(2), ['max_retries' => 0], $this->closedEmails()); - - $this->assertSame('delivery_unavailable', $error->getErrorCode()); - $this->assertCount(1, $this->requests); - $this->assertSame(['unconfirmed', 'unconfirmed'], self::statuses($error->getResults())); - } - public function testARequestRefusedAsAWholeThrowsWithTheResultsSoFar(): void { $this->reply(self::allQueued(), self::wholeCall(429, 'quota_limited')); @@ -1034,89 +994,37 @@ public function testARequestRefusedAsAWholeThrowsWithTheResultsSoFar(): void public function testARefusalOfTheWholeRequestAfterALostAnswerKeepsItsRecipientsUnconfirmed(): void { - $this->reply(self::networkError(), self::wholeCall(429, 'quota_limited'), self::statusFound('m0')); + $this->reply(self::networkError(), self::wholeCall(429, 'quota_limited')); $error = $this->batchError(self::recipients(1)); [$result] = $error->getResults(); - $this->assertSame(['unconfirmed', 'm0'], [$result->getStatus(), $result->getMessageId()]); + $this->assertSame(['unconfirmed', null], [$result->getStatus(), $result->getMessageId()]); $this->assertSame('delivery_unavailable', $result->getError()->getErrorCode()); $this->assertSame('quota_limited', $result->getLaterError()->getErrorCode()); - $this->assertSame(['key-0'], $this->readsByKey()); + $this->assertSame([self::BATCH_URL, self::BATCH_URL], $this->requestUrls()); } - public function testALostAnswerAfterTheRetriesReadsEachEmailByItsKey(): void + public function testALostAnswerAfterTheRetriesTellsEachRecipientToSendAgainWithItsKey(): void { - $statusByKey = static function (string $url): array { - return str_ends_with($url, '=key-0') ? self::statusFound('m0') : self::wholeCall(404, 'not_found'); - }; - $this->reply(self::networkError(), self::networkError(), self::networkError(), $statusByKey, $statusByKey); + $this->reply(self::networkError(), self::networkError(), self::networkError()); $error = $this->batchError(self::recipients(2)); $this->assertSame('network_error', $error->getErrorCode()); - $this->assertSame(['key-0', 'key-1'], $this->readsByKey()); + $this->assertSame([self::BATCH_URL, self::BATCH_URL, self::BATCH_URL], $this->requestUrls()); $this->assertSame( - [['unconfirmed', 'm0'], ['unconfirmed', null]], - array_map(static fn($r): array => [$r->getStatus(), $r->getMessageId()], $error->getResults()) + [['unconfirmed', null, 'key-0'], ['unconfirmed', null, 'key-1']], + array_map( + static fn($r): array => [$r->getStatus(), $r->getMessageId(), $r->getIdempotencyKey()], + $error->getResults() + ) ); - $this->assertSame('delivery_unavailable', $error->getResults()[1]->getError()->getErrorCode()); - } - - public static function statusesReadByKey(): array - { - return [ - 'sent' => [self::statusFound('m0')], - 'refused' => [self::statusFound('m0', 'failed', 'recipient_suppressed')], - ]; - } - - #[DataProvider('statusesReadByKey')] - public function testAStatusReadByKeyFillsInOnlyTheMessageId(array $read): void - { - $this->reply(self::networkError(), $read); - - $error = $this->batchError(self::recipients(1), ['max_retries' => 0]); - - [$result] = $error->getResults(); - $this->assertSame(['unconfirmed', 'm0'], [$result->getStatus(), $result->getMessageId()]); - $this->assertSame('delivery_unavailable', $result->getError()->getErrorCode()); - $this->assertNull($result->getLaterError()); - } - - public function testAnEmailWithAMessageIdIsNotReadByItsKey(): void - { - $this->reply( - self::ok(self::refused('m0', 'delivery_unavailable', 503, true), ...array_fill(0, 99, self::queued('m'))), - self::networkError(), - ...array_fill(0, 50, self::wholeCall(404, 'not_found')) + $this->assertSame( + "PostHog didn't confirm this email, so it may still go out. Send it again with the same idempotency_key " + . 'within 24 hours, so it goes out once.', + $error->getResults()[1]->getError()->getMessage() ); - - $error = $this->batchError(self::recipients(150), ['max_retries' => 0]); - - $this->assertSame(array_map(static fn(int $i): string => "key-$i", range(100, 149)), $this->readsByKey()); - $first = $error->getResults()[0]; - $this->assertSame(['unconfirmed', 'm0'], [$first->getStatus(), $first->getMessageId()]); - } - - public function testReadingByKeyStopsWhenPostHogStaysUnreachable(): void - { - $unavailable = self::wholeCall(503, 'delivery_unavailable'); - $this->reply($unavailable, $unavailable, $unavailable, self::networkError()); - - $error = $this->batchError(self::recipients(3), ['max_retries' => 2]); - - $this->assertCount(4, $this->requests); - $this->assertSame(['unconfirmed', 'unconfirmed', 'unconfirmed'], self::statuses($error->getResults())); - } - - public function testAKeyWithReservedCharactersIsEncodedInTheStatusRead(): void - { - $this->reply(self::networkError(), self::wholeCall(404, 'not_found')); - - $this->batchError([['to' => 'a@example.com', 'idempotency_key' => 'order#1&x=2']], ['max_retries' => 0]); - - $this->assertSame(['order#1&x=2'], $this->readsByKey()); } public function testBatchUnavailableIsNotRetriedAndSaysToSendEachEmailOnItsOwn(): void @@ -1168,7 +1076,7 @@ public static function retriesAfterAnUnconfirmingAttempt(): array public function testARetryThatLosesItsAnswerAgainIsTheLaterError(): void { - $this->reply(self::networkError(), self::networkError(), self::wholeCall(404, 'not_found')); + $this->reply(self::networkError(), self::networkError()); $error = $this->batchError(self::recipients(1), ['max_retries' => 1]); @@ -1185,7 +1093,7 @@ public function testARetryThatCannotConfirmEitherIsTheLaterError( mixed $retry, string $laterCode ): void { - $this->reply($first, $retry, self::wholeCall(404, 'not_found')); + $this->reply($first, $retry); $error = $this->batchError(self::recipients(1), ['max_retries' => 1]); @@ -1195,51 +1103,9 @@ public function testARetryThatCannotConfirmEitherIsTheLaterError( $this->assertSame($laterCode, $result->getLaterError()?->getErrorCode()); } - public static function lookupFailures(): array - { - return [ - 'a promoted deprecation' => [new ErrorException('Constant DATE_RFC7231 is deprecated', 0, E_DEPRECATED)], - 'a missing class' => [new Error('Class "Symfony\\Component\\Clock\\Clock" not found')], - ]; - } - - #[DataProvider('lookupFailures')] - public function testALookupThatThrowsStopsTheReadsAndKeepsEveryResult(Throwable $failure): void - { - $this->reply( - self::ok(self::queued('m0'), self::notConfirmed(null), self::notConfirmed(null)), - static function () use ($failure): never { - throw $failure; - } - ); - - $result = $this->batch(self::recipients(3), ['max_retries' => 0]); - - $this->assertSame(['key-1'], $this->readsByKey()); - $this->assertSame( - [['queued', 'm0'], ['unconfirmed', null], ['unconfirmed', null]], - array_map(static fn($r): array => [$r->getStatus(), $r->getMessageId()], $result->getResults()) - ); - } - - #[DataProvider('lookupFailures')] - public function testALookupThatThrowsAfterAFailedRequestStillThrowsTheBatchError(Throwable $failure): void - { - $this->reply(self::networkError(), static function () use ($failure): never { - throw $failure; - }); - - $error = $this->batchError(self::recipients(2), ['max_retries' => 0]); - - $this->assertSame('network_error', $error->getErrorCode()); - $this->assertSame(['key-0'], $this->readsByKey()); - $this->assertSame(['unconfirmed', 'unconfirmed'], self::statuses($error->getResults())); - } - public function testAnAnswerWithoutAResultPerRecipientLeavesTheRequestUnconfirmed(): void { - $notFound = self::wholeCall(404, 'not_found'); - $this->reply(self::ok(self::queued('m0')), $notFound, $notFound); + $this->reply(self::ok(self::queued('m0'))); $error = $this->batchError(self::recipients(2), ['max_retries' => 0]); @@ -1249,7 +1115,7 @@ public function testAnAnswerWithoutAResultPerRecipientLeavesTheRequestUnconfirme [null, null], array_map(static fn($r): ?EmailError => $r->getLaterError(), $error->getResults()) ); - $this->assertSame(['key-0', 'key-1'], $this->readsByKey()); + $this->assertSame([self::BATCH_URL], $this->requestUrls()); } public function testWarningsReachTheCallerOnce(): void From 15ca14388ca045d5d34530191e8fc3685d7173bc Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:18:18 +0100 Subject: [PATCH 18/44] fix(emails): free each batch request and keep the in-flight cause Co-Authored-By: Claude Opus 5.5 --- lib/Emails.php | 1 + lib/Internal/EmailBatch.php | 40 ++++++------ test/EmailsBatchTest.php | 118 ++++++++++++++++++++++++++---------- 3 files changed, 109 insertions(+), 50 deletions(-) diff --git a/lib/Emails.php b/lib/Emails.php index 3a54aac..ca640ca 100644 --- a/lib/Emails.php +++ b/lib/Emails.php @@ -1169,6 +1169,7 @@ private function sendBatch(EmailBatch $run, string $appHost, string $secretKey, $run->stop($position, $error); throw $run->failure($error); } + unset($body, $attemptOnce); } } diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index 4492f94..38dc9f8 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -53,20 +53,6 @@ public static function prepare(array $shared, mixed $recipients): self field: 'recipients' ); } - $encoded = []; - $size = strlen('{"recipients":[]}'); - foreach ($shared as $name => $value) { - $encoded[$name] = self::encode($value, 'The email'); - $size += strlen(self::encode((string) $name, 'The email')) + strlen($encoded[$name]) + strlen(':,'); - } - if ($size > self::MAX_REQUEST_BYTES) { - throw self::sharedTooLarge($encoded); - } - $pairs = []; - foreach ($encoded as $name => $json) { - $pairs[] = self::encode((string) $name, 'The email') . ':' . $json; - } - $opening = '{' . implode(',', [...$pairs, '"recipients":[']); $isTemplateForm = array_key_exists('template_id', $shared); $members = []; $firstWithKey = []; @@ -84,6 +70,20 @@ public static function prepare(array $shared, mixed $recipients): self } $members[] = $member; } + $encoded = []; + $size = strlen('{"recipients":[]}'); + foreach ($shared as $name => $value) { + $encoded[$name] = self::encode($value, 'The email'); + $size += strlen(self::encode((string) $name, 'The email')) + strlen($encoded[$name]) + strlen(':,'); + } + if ($size > self::MAX_REQUEST_BYTES) { + throw self::sharedTooLarge($encoded); + } + $pairs = []; + foreach ($encoded as $name => $json) { + $pairs[] = self::encode((string) $name, 'The email') . ':' . $json; + } + $opening = '{' . implode(',', [...$pairs, '"recipients":[']); return new self($members, $opening); } @@ -223,9 +223,14 @@ public function requestCount(): int public function requestBody(int $position): string { - $wires = array_map(fn(int $index): string => $this->members[$index]['wire'], $this->requests[$position]); + $parts = [$this->opening]; + foreach ($this->requests[$position] as $index) { + $parts[] = $this->members[$index]['wire']; + $parts[] = ','; + } + $parts[count($parts) - 1] = ']}'; - return $this->opening . implode(',', $wires) . ']}'; + return implode('', $parts); } public function lost(int $position, EmailError $error): void @@ -233,7 +238,8 @@ public function lost(int $position, EmailError $error): void $this->recordLaterError($position, $error); foreach ($this->requests[$position] as $index) { if (!$this->isUnconfirmed($index)) { - $this->set($index, 'unconfirmed', error: self::unconfirmed(null)); + $cause = $error->getErrorCode() === self::IN_FLIGHT ? $error : self::unconfirmed(null); + $this->set($index, 'unconfirmed', error: $cause); } } } diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index b9a95c1..0a6b021 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -628,8 +628,7 @@ public function jsonSerialize(): mixed public function testABatchOf10000RecipientsFitsIn24MibOfMemory(): void { - $script = tempnam(sys_get_temp_dir(), 'posthog-emails-batch-'); - file_put_contents($script, <<<'PHP' + $script = <<<'PHP' getResults(), static fn($email): bool => $email->getStatus() === 'queued')); echo json_encode([$requests, $queued]); -PHP); - try { - $command = escapeshellarg(PHP_BINARY) . ' -d memory_limit=24M ' . escapeshellarg($script) . ' ' - . escapeshellarg(__DIR__ . '/../vendor/autoload.php') . ' 2>&1'; - exec($command, $output, $exitCode); - - $this->assertSame([0, '[100,10000]'], [$exitCode, implode("\n", $output)]); - } finally { - unlink($script); - } +PHP; + $this->assertSame([0, '[100,10000]'], self::runWithMemoryLimit($script, '24M')); } public function testARecipientWithA10MibDistinctIdOfNulBytesFailsWithin128MibOfMemory(): void { - $script = tempnam(sys_get_temp_dir(), 'posthog-emails-batch-'); - file_put_contents($script, <<<'PHP' + $script = <<<'PHP' [500, '', []]); @@ -682,25 +672,16 @@ public function testARecipientWithA10MibDistinctIdOfNulBytesFailsWithin128MibOfM 'template_id' => '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b', ])->getResults()[0]; echo json_encode([$recipient->getStatus(), $recipient->getError()->getErrorCode(), $recipient->getError()->getField()]); -PHP); - try { - $command = escapeshellarg(PHP_BINARY) . ' -d memory_limit=128M ' . escapeshellarg($script) . ' ' - . escapeshellarg(__DIR__ . '/../vendor/autoload.php') . ' 2>&1'; - exec($command, $output, $exitCode); - - $this->assertSame( - [0, '["failed","content_too_large","recipients__0__distinct_id"]'], - [$exitCode, implode("\n", $output)] - ); - } finally { - unlink($script); - } +PHP; + $this->assertSame( + [0, '["failed","content_too_large","recipients__0__distinct_id"]'], + self::runWithMemoryLimit($script, '128M') + ); } public function testA32MibHtmlIsRefusedWithin128MibOfMemory(): void { - $script = tempnam(sys_get_temp_dir(), 'posthog-emails-batch-'); - file_put_contents($script, <<<'PHP' + $script = <<<'PHP' getErrorCode(), $error->getField()]); } -PHP); +PHP; + $this->assertSame([0, '[0,"content_too_large","html"]'], self::runWithMemoryLimit($script, '128M')); + } + + public function testEachRequestOfABatchIsBuiltAfterThePreviousOneIsFreed(): void + { + $script = <<<'PHP' + "msg_$key", 'status' => 'queued']; + } + + return [200, json_encode(['results' => $slots]), []]; +}); +$recipients = []; +for ($index = 0; $index < 8; $index++) { + $recipients[] = [ + 'to' => "user$index@example.com", + 'idempotency_key' => "key-$index", + 'template_data' => ['note' => str_repeat(chr(97 + $index), 1010000)], + ]; +} +$result = $emails->batch(['recipients' => $recipients, 'template_id' => '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b']); +$queued = count(array_filter($result->getResults(), static fn($email): bool => $email->getStatus() === 'queued')); +echo json_encode([$requests, $queued]); +PHP; + + $this->assertSame([0, '[2,8]'], self::runWithMemoryLimit($script, '29M')); + } + + public function testARecipientWithoutToIsRefusedBeforeSharedContentIsEncoded(): void + { + $script = <<<'PHP' + [500, '', []]); +try { + $emails->batch([ + 'recipients' => [['distinct_id' => 'user-1']], + 'template_key' => 'news', + 'subject' => 'News', + 'html' => str_repeat("\0", 21 * 1024 * 1024), + ]); +} catch (PostHog\EmailError $error) { + echo json_encode([$error->getErrorCode(), $error->getField()]); +} +PHP; + + $this->assertSame([0, '["invalid_recipient","recipients__0__to"]'], self::runWithMemoryLimit($script, '128M')); + } + + /** + * @return array{int, string} + */ + private static function runWithMemoryLimit(string $code, string $limit): array + { + $script = tempnam(sys_get_temp_dir(), 'posthog-emails-batch-'); + file_put_contents($script, $code); try { - $command = escapeshellarg(PHP_BINARY) . ' -d memory_limit=128M ' . escapeshellarg($script) . ' ' + $command = escapeshellarg(PHP_BINARY) . " -d memory_limit=$limit " . escapeshellarg($script) . ' ' . escapeshellarg(__DIR__ . '/../vendor/autoload.php') . ' 2>&1'; exec($command, $output, $exitCode); - $this->assertSame([0, '[0,"content_too_large","html"]'], [$exitCode, implode("\n", $output)]); + return [$exitCode, implode("\n", $output)]; } finally { unlink($script); } @@ -880,10 +929,12 @@ public static function attemptsAfterAnInFlightAnswer(): array return [ 'a refusal after an in-flight answer' => [ [self::wholeCall(409, 'idempotency_key_in_flight'), self::wholeCall(429, 'quota_limited')], + 'idempotency_key_in_flight', 'quota_limited', ], 'an in-flight answer after a 503' => [ [self::wholeCall(503, 'delivery_unavailable'), self::wholeCall(409, 'idempotency_key_in_flight')], + 'delivery_unavailable', 'idempotency_key_in_flight', ], ]; @@ -892,6 +943,7 @@ public static function attemptsAfterAnInFlightAnswer(): array #[DataProvider('attemptsAfterAnInFlightAnswer')] public function testTheAttemptAfterTheOneThatLeftARecipientUnconfirmedIsItsLaterError( array $answers, + string $code, string $laterCode ): void { $this->reply(...$answers); @@ -900,7 +952,7 @@ public function testTheAttemptAfterTheOneThatLeftARecipientUnconfirmedIsItsLater [$result] = $error->getResults(); $this->assertSame('unconfirmed', $result->getStatus()); - $this->assertSame('delivery_unavailable', $result->getError()->getErrorCode()); + $this->assertSame($code, $result->getError()->getErrorCode()); $this->assertSame($laterCode, $result->getLaterError()->getErrorCode()); $this->assertSame([self::BATCH_URL, self::BATCH_URL], $this->requestUrls()); } From 629afe96a6ed17af58ad41e83edfcf3deed27a1a Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:31:12 +0100 Subject: [PATCH 19/44] fix(emails): join each batch recipient's json in one allocation Co-Authored-By: Claude Opus 5.5 --- lib/Internal/EmailBatch.php | 7 ++++--- test/EmailsBatchTest.php | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index 38dc9f8..c0e61b1 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -147,12 +147,13 @@ private static function member(int $index, mixed $recipient, bool $isTemplateFor */ private static function joined(array $values): string { - $pairs = []; + $parts = []; foreach ($values as $name => $json) { - $pairs[] = "\"$name\":$json"; + array_push($parts, $parts === [] ? '{' : ',', "\"$name\":", $json); } + $parts[] = '}'; - return '{' . implode(',', $pairs) . '}'; + return implode('', $parts); } private static function templateData(int $index, mixed $data, bool $isTemplateForm): array|object diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index 0a6b021..0af0f4e 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -741,6 +741,27 @@ public function testEachRequestOfABatchIsBuiltAfterThePreviousOneIsFreed(): void $this->assertSame([0, '[2,8]'], self::runWithMemoryLimit($script, '29M')); } + public function testARecipientIsEncodedWithoutExtraCopiesOfItsData(): void + { + $script = <<<'PHP' + [ + 200, + '{"results":[{"message_id":"msg_1","status":"queued"}]}', + [], +]); +$result = $emails->batch([ + 'recipients' => [['to' => 'user@example.com', 'template_data' => ['note' => str_repeat('x', 3950000)]]], + 'template_id' => '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b', +]); +echo $result->getResults()[0]->getStatus(); +PHP; + + $this->assertSame([0, 'queued'], self::runWithMemoryLimit($script, '32M')); + } + public function testARecipientWithoutToIsRefusedBeforeSharedContentIsEncoded(): void { $script = <<<'PHP' From 8c9d6804a2124a72130e976842143678f86d5006 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:48:47 +0100 Subject: [PATCH 20/44] fix(emails): tell batch recipients left in flight to reuse their key Co-Authored-By: Claude Opus 5.5 --- lib/Internal/EmailBatch.php | 21 ++++++++++++++++++--- test/EmailsBatchTest.php | 9 +++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index c0e61b1..c20c192 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -19,6 +19,7 @@ final class EmailBatch private const MAX_REQUEST_BYTES = 4 * 1024 * 1024; private const RECIPIENT_FIELDS = ['to', 'distinct_id', 'idempotency_key', 'template_data']; private const UNCONFIRMED_CODES = ['idempotency_key_in_flight', 'delivery_unavailable', 'api_error']; + private const SEND_AGAIN = 'Send it again with the same idempotency_key within 24 hours, so it goes out once.'; private const IN_FLIGHT = 'idempotency_key_in_flight'; private const JSON_FLAGS = JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE; private const SEND_SINGLY = "send each email the batch didn't queue with emails()->send() and its recipient's " @@ -239,7 +240,7 @@ public function lost(int $position, EmailError $error): void $this->recordLaterError($position, $error); foreach ($this->requests[$position] as $index) { if (!$this->isUnconfirmed($index)) { - $cause = $error->getErrorCode() === self::IN_FLIGHT ? $error : self::unconfirmed(null); + $cause = $error->getErrorCode() === self::IN_FLIGHT ? self::inFlight($error) : self::unconfirmed(null); $this->set($index, 'unconfirmed', error: $cause); } } @@ -468,12 +469,26 @@ private static function unconfirmed(?string $messageId): EmailError { return new EmailError( 'delivery_unavailable', - "PostHog didn't confirm this email, so it may still go out. Send it again with the same idempotency_key " - . 'within 24 hours, so it goes out once.', + "PostHog didn't confirm this email, so it may still go out. " . self::SEND_AGAIN, messageId: $messageId ); } + private static function inFlight(EmailError $error): EmailError + { + return new EmailError( + $error->getErrorCode(), + $error->getMessage(), + $error->getStatusCode(), + $error->getWhy(), + $error->getFix() ?? self::SEND_AGAIN, + $error->getDocsUrl(), + $error->getField(), + $error->getRetryAfterMs(), + $error + ); + } + /** * @param array $encoded */ diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index 0af0f4e..2e94426 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -942,6 +942,15 @@ public function testAWholeRequestInFlightAnswerLeavesItsRecipientsUnconfirmed(): $error->getResults() ) ); + $recipientError = $error->getResults()[0]->getError(); + $this->assertSame( + [ + 'idempotency_key_in_flight', + 'Nope.', + 'Send it again with the same idempotency_key within 24 hours, so it goes out once.', + ], + [$recipientError->getErrorCode(), $recipientError->getMessage(), $recipientError->getFix()] + ); $this->assertSame([self::BATCH_URL], $this->requestUrls()); } From d19118955ff97f8eff23a18751bc5f3760f52ea4 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:01:09 +0100 Subject: [PATCH 21/44] fix(emails): treat only a 409 in flight as unconfirmed in a batch Co-Authored-By: Claude Opus 5.5 --- lib/Internal/EmailBatch.php | 2 +- test/EmailsBatchTest.php | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index c20c192..0d87e31 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -255,7 +255,7 @@ public function answer(int $position, int $status, string $body, array $headers) $fields = EmailReplies::fields($body); if ($status < 200 || $status >= 300) { $error = self::requestError($fields, $status, $headers, $indices); - if ($status >= 500 || $error->getErrorCode() === self::IN_FLIGHT) { + if ($status >= 500 || ($status === 409 && $error->getErrorCode() === self::IN_FLIGHT)) { $this->lost($position, $error); } else { $this->recordLaterError($position, $error); diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index 2e94426..7c9cd54 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -1109,6 +1109,16 @@ public function testALostAnswerAfterTheRetriesTellsEachRecipientToSendAgainWithI ); } + public function testAnInFlightCodeOnAnAnswerOtherThanA409RefusesTheRequest(): void + { + $this->reply(self::wholeCall(400, 'idempotency_key_in_flight')); + + $error = $this->batchError(self::recipients(2), ['max_retries' => 2]); + + $this->assertCount(1, $this->requests); + $this->assertSame(['failed', 'failed'], self::statuses($error->getResults())); + } + public function testBatchUnavailableIsNotRetriedAndSaysToSendEachEmailOnItsOwn(): void { $this->reply(self::wholeCall(409, 'batch_unavailable')); From f0ec7b2f1c51953d1a98e813e4aef1dcf24abb2f Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:19:10 +0100 Subject: [PATCH 22/44] fix(emails): refuse batch recipients nested past the json depth Co-Authored-By: Claude Opus 5.5 --- lib/Internal/EmailBatch.php | 6 +++--- test/EmailsBatchTest.php | 30 ++++++++++++++++++++++++++---- 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index 0d87e31..7e75d45 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -126,7 +126,7 @@ private static function member(int $index, mixed $recipient, bool $isTemplateFor $sizes = []; $bytes = strlen('{}') + count($wire) - 1; foreach ($wire as $name => $value) { - $values[$name] = self::encode($value, "recipients[$index]"); + $values[$name] = self::encode($value, "recipients[$index]", 511); $sizes[$name === 'message_data' ? 'template_data' : $name] = strlen($values[$name]); $bytes += strlen("\"$name\":") + strlen($values[$name]); } @@ -180,10 +180,10 @@ private static function templateData(int $index, mixed $data, bool $isTemplateFo return $data === [] ? (object) [] : $data; } - private static function encode(mixed $payload, string $what): string + private static function encode(mixed $payload, string $what, int $depth = 512): string { try { - return json_encode($payload, self::JSON_FLAGS); + return json_encode($payload, self::JSON_FLAGS, $depth); } catch (JsonException $exception) { throw new EmailError( 'invalid_form', diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index 7c9cd54..df530d0 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -717,7 +717,10 @@ public function testEachRequestOfABatchIsBuiltAfterThePreviousOneIsFreed(): void ?string $body ) use (&$requests): array { $requests++; - preg_match_all('/"idempotency_key":"(key-\\d)"/', $body, $keys); + if (function_exists('json_validate') && !json_validate($body)) { + return [400, '{"type":"validation_error","code":"invalid_json","detail":"Bad JSON."}', []]; + } + preg_match_all('/"idempotency_key"\\s*:\\s*"(key-\\d)"/', $body, $keys); $slots = []; foreach ($keys[1] as $key) { $slots[] = ['message_id' => "msg_$key", 'status' => 'queued']; @@ -749,17 +752,36 @@ public function testARecipientIsEncodedWithoutExtraCopiesOfItsData(): void $appMemory = str_repeat('b', 14 * 1024 * 1024); $emails = new PostHog\Emails('phs_secret', 'us.i.posthog.com', transport: static fn(): array => [ 200, - '{"results":[{"message_id":"msg_1","status":"queued"}]}', + '{"results":[{"error":{"code":"content_too_large","detail":"Too large.","status":413}}]}', [], ]); $result = $emails->batch([ 'recipients' => [['to' => 'user@example.com', 'template_data' => ['note' => str_repeat('x', 3950000)]]], 'template_id' => '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b', ]); -echo $result->getResults()[0]->getStatus(); +echo $result->getResults()[0]->getStatus(), ' ', $result->getResults()[0]->getError()->getErrorCode(); PHP; - $this->assertSame([0, 'queued'], self::runWithMemoryLimit($script, '32M')); + $this->assertSame([0, 'failed content_too_large'], self::runWithMemoryLimit($script, '32M')); + } + + public function testARecipientNestedDeeperThanItsEncodingAllowsIsRefusedBeforeAnyRequest(): void + { + $nested = 'v'; + for ($level = 1; $level < 512; $level++) { + $nested = [$nested]; + } + + try { + $this->batch([ + ...self::recipients(1), + ['to' => 'deep@example.com', 'idempotency_key' => 'key-deep', 'template_data' => ['deep' => $nested]], + ]); + $this->fail('Expected invalid_form'); + } catch (EmailError $error) { + $this->assertSame('invalid_form', $error->getErrorCode()); + } + $this->assertSame([], $this->requests); } public function testARecipientWithoutToIsRefusedBeforeSharedContentIsEncoded(): void From de0ad88b5a24fa8ec350050f83fdde04f8ef12ce Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:40:41 +0100 Subject: [PATCH 23/44] feat(emails): send a batch as one request of at most 100 recipients More than 100 recipients is refused before any request. A refusal of the whole batch, such as a 413, is the error, with every recipient's result. The chunk loop, not_attempted, getLaterError() and the client-side 4 MiB sizing are gone. Co-Authored-By: Claude Opus 5.5 --- .changeset/email-batch-sends.md | 2 +- README.md | 6 +- api/public-api.json | 17 -- lib/BatchEmailResult.php | 16 +- lib/EmailBatchError.php | 9 +- lib/EmailError.php | 4 +- lib/Emails.php | 56 ++-- lib/Internal/EmailBatch.php | 262 ++++------------- lib/SendBatchResult.php | 2 +- test/EmailsBatchTest.php | 491 +++----------------------------- 10 files changed, 125 insertions(+), 740 deletions(-) diff --git a/.changeset/email-batch-sends.md b/.changeset/email-batch-sends.md index 923f36a..aca9826 100644 --- a/.changeset/email-batch-sends.md +++ b/.changeset/email-batch-sends.md @@ -2,4 +2,4 @@ "posthog-php": minor --- -Transactional email: `emails()->batch()` sends the same email to many recipients, one email each, from a template with `template_data` per recipient or from content in your code. The client sends at most 100 recipients and 4 MiB per request, one request after another, gives each recipient an idempotency key that every retry reuses, and returns a `SendBatchResult` with a `BatchEmailResult` per recipient: `queued`, `failed`, `unconfirmed` or `not_attempted`. A request that fails as a whole throws `EmailBatchError` with every recipient's result. +Transactional email: `emails()->batch()` sends the same email to many recipients, one email each, from a template with `template_data` per recipient or from content in your code. A call takes up to 100 recipients and sends one request. The client gives each recipient an idempotency key that every retry reuses, and returns a `SendBatchResult` with a `BatchEmailResult` per recipient: `queued`, `failed` or `unconfirmed`. A batch PostHog refuses as a whole, such as `too_large`, throws `EmailBatchError` with every recipient's result. diff --git a/README.md b/README.md index 2d2f2af..555e6af 100644 --- a/README.md +++ b/README.md @@ -106,10 +106,10 @@ foreach ($result->getResults() as $email) { ``` - **Recipients.** Each recipient has `to` and optional `distinct_id`, `idempotency_key` and `template_data`. A recipient's `template_data` is merged over the shared `template_data`, and its keys replace the shared ones. With `template_key`, the content is the same for every recipient, so a recipient can't carry `template_data`. A batch takes no `cc`, `bcc`, `attachments` or `scheduled_at`: send those emails with `send()`. -- **Requests.** The client sends at most 100 recipients and 4 MiB of JSON per request, one request after another, and waits at least 45 seconds for each answer. Shared content over 4 MiB throws `content_too_large` before any request. A recipient whose email alone is over 4 MiB is `failed` with `content_too_large`. +- **Requests.** A batch takes 1 to 100 recipients and goes out in one request. The client waits at least 45 seconds for the answer. More than 100 recipients throws `invalid_recipients` before any request. - **Idempotency keys.** Every retry reuses each recipient's key, so a retry never queues an email twice. Without a key, the client makes one that covers its own retries but not a second call. When a batch may be cut off and run again, pass keys you store: send it again with the same key within 24 hours, so it goes out once. Each recipient of a call needs a different key. Build each key from an ID you store with the job, such as the digest's own ID, never from the time of the run: a retry after midnight would make new keys and send the emails again. Never reuse a key for another email: PostHog sends one email per key, so the other doesn't go out. PostHog usually refuses it with `idempotency_key_reused`, but two sends that arrive at the same time can both answer `queued`. -- **Statuses.** `getStatus()` is `queued` when PostHog accepted the email, `failed` when it refused it (`getError()` says why, such as a suppressed address), `unconfirmed` when the client can't tell, such as after a lost answer, and `not_attempted` when an earlier request of the batch failed. Send each `unconfirmed` email again with the same key within 24 hours, so it goes out once. `getWarnings()` holds PostHog's warnings, each once. -- **Errors.** A request that fails as a whole, such as a rate limit past its retries, stops the batch and throws `PostHog\EmailBatchError`, whose `getResults()` holds every recipient. `batch_unavailable` (409) means the project can't send batches yet, and is never retried. `not_found` (404) means the template doesn't exist or batch sends are off. For both, send each email the batch didn't queue with `send()` and its recipient's `idempotency_key`. +- **Statuses.** `getStatus()` is `queued` when PostHog accepted the email, `failed` when it refused it (`getError()` says why, such as a suppressed address), and `unconfirmed` when the client can't tell, such as after a lost answer. Send each `unconfirmed` email again with the same key within 24 hours, so it goes out once. `getWarnings()` holds PostHog's warnings. +- **Errors.** When PostHog refuses the batch as a whole, such as a rate limit past its retries, `batch()` throws `PostHog\EmailBatchError`, whose `getResults()` holds every recipient. `too_large` (413) means the batch is larger than PostHog takes: split the recipients into smaller batches. `batch_unavailable` (409) means the project can't send batches yet, and is never retried. `not_found` (404) means the template doesn't exist or batch sends are off. For both, send each email the batch didn't queue with `send()` and its recipient's `idempotency_key`. ## Questions? diff --git a/api/public-api.json b/api/public-api.json index 1c8e7ad..b51923a 100644 --- a/api/public-api.json +++ b/api/public-api.json @@ -87,16 +87,6 @@ "default": null, "defaultConstant": null, "hasDefault": true - }, - { - "name": "laterError", - "type": "?PostHog\\EmailError", - "byReference": false, - "variadic": false, - "optional": true, - "default": null, - "defaultConstant": null, - "hasDefault": true } ] }, @@ -121,13 +111,6 @@ "returnType": "int", "parameters": [] }, - "getLaterError": { - "static": false, - "abstract": false, - "final": false, - "returnType": "?PostHog\\EmailError", - "parameters": [] - }, "getMessageId": { "static": false, "abstract": false, diff --git a/lib/BatchEmailResult.php b/lib/BatchEmailResult.php index 498a28d..3fcd0b6 100644 --- a/lib/BatchEmailResult.php +++ b/lib/BatchEmailResult.php @@ -12,8 +12,6 @@ * - `unconfirmed`: the client can't tell whether PostHog queued the email, such as after a lost answer. It may * still go out. Send it again with the same idempotency key within 24 hours, so it goes out once. * getMessageId() is the email's ID when PostHog's answer named one. - * getLaterError() holds what a later attempt in the same call answered, which describes only that attempt. - * - `not_attempted`: an earlier request of the batch failed, so the client sent nothing for this recipient. */ class BatchEmailResult { @@ -27,8 +25,7 @@ public function __construct( private string $status, private ?string $messageId = null, private bool $replayed = false, - private ?EmailError $error = null, - private ?EmailError $laterError = null + private ?EmailError $error = null ) { } @@ -58,7 +55,7 @@ public function getIdempotencyKey(): string } /** - * `queued`, `failed`, `unconfirmed` or `not_attempted`. + * `queued`, `failed` or `unconfirmed`. */ public function getStatus(): string { @@ -91,13 +88,4 @@ public function getError(): ?EmailError { return $this->error; } - - /** - * For an `unconfirmed` email, what a later attempt in the same call answered, such as `idempotency_key_reused`. - * It describes only that attempt: the first may still have queued the email. - */ - public function getLaterError(): ?EmailError - { - return $this->laterError; - } } diff --git a/lib/EmailBatchError.php b/lib/EmailBatchError.php index 07dbb93..b8c8d8c 100644 --- a/lib/EmailBatchError.php +++ b/lib/EmailBatchError.php @@ -3,11 +3,10 @@ namespace PostHog; /** - * A request of Emails::batch() failed as a whole, so the batch stopped. + * PostHog refused a call of Emails::batch() as a whole, or its answer was lost. * - * The code, message and other fields are that request's error. getResults() holds every recipient: those of - * earlier requests as PostHog answered them, those of the failed request as `failed`, or `unconfirmed` where an - * attempt may have queued them, and the rest as `not_attempted`. + * The code, message and other fields are the request's error. getResults() holds every recipient: `failed`, or + * `unconfirmed` where an attempt may have queued it. */ class EmailBatchError extends EmailError { @@ -43,7 +42,7 @@ public function getResults(): array } /** - * The warnings PostHog returned about the requests that went out, each once. + * The warnings PostHog returned about the batch. * * @return list */ diff --git a/lib/EmailError.php b/lib/EmailError.php index 5d1569c..3da7928 100644 --- a/lib/EmailError.php +++ b/lib/EmailError.php @@ -92,7 +92,7 @@ public function getErrorName(): string /** * PostHog's error code, such as `quota_limited`, or an SDK code such as `missing_secret_key`, * `missing_app_host`, `client_disabled`, `client_closed`, `network_error`, `api_error`, `attachment_upload_failed`, - * `scheduling_requires_cloud`, `schedule_not_confirmed`, `not_attempted` or an `invalid_*` argument code. + * `scheduling_requires_cloud`, `schedule_not_confirmed` or an `invalid_*` argument code. */ public function getErrorCode(): string { @@ -175,7 +175,7 @@ private static function nameFor(?int $status, string $code): string if ($status === null) { return match (true) { in_array($code, ['network_error', 'delivery_unavailable'], true) => 'service_unavailable', - $code === 'content_too_large', str_starts_with($code, 'invalid_') => 'validation_error', + str_starts_with($code, 'invalid_') => 'validation_error', default => 'application_error', }; } diff --git a/lib/Emails.php b/lib/Emails.php index b0f6a48..f214094 100644 --- a/lib/Emails.php +++ b/lib/Emails.php @@ -412,11 +412,10 @@ public function get(string $messageId): EmailStatus * A batch takes no `cc`, `bcc`, `attachments` or `scheduled_at`, and no `to`, `distinct_id` or * `idempotency_key` of its own: each throws `invalid_form` before any request. * - * `recipients` is a list of 1 or more recipients, each an array with `to` and optional `distinct_id`, - * `idempotency_key` and `template_data`. A null value counts as left out. The client sends the recipients in - * requests of at most 100 recipients and 4 MiB of JSON, one request after another, and waits 45 seconds for - * each answer, or `email_request_timeout_ms` when that is longer. `max_retries` overrides the client's - * retries for each request. + * `recipients` is a list of 1 to 100 recipients, each an array with `to` and optional `distinct_id`, + * `idempotency_key` and `template_data`. A null value counts as left out. The client sends the batch in one + * request and waits 45 seconds for the answer, or `email_request_timeout_ms` when that is longer. + * `max_retries` overrides the client's retries for the request. * * Each recipient's `idempotency_key` is 1 to 255 visible ASCII characters, a different one for each recipient * of the call, and every retry reuses it, so a retry never queues an email twice. Without it, the client makes @@ -434,14 +433,13 @@ public function get(string $messageId): EmailStatus * - `failed`: PostHog refused it, and getError() says why, such as a suppressed address. * - `unconfirmed`: the client can't tell whether PostHog accepted it, such as after a lost answer, or when * another request still holds its key. Send it again with the same key within 24 hours, so it goes out once. - * - `not_attempted`: an earlier request of the batch failed, so the client sent nothing for it. * - * A request that fails as a whole, such as a rate limit past its retries, stops the batch and throws - * EmailBatchError, whose getResults() holds every recipient. The code `batch_unavailable` (409) means the project - * can't send batches yet, and is never retried. `not_found` (404) means the template doesn't exist or batch - * sends are off for the project. For both, send each email the batch didn't queue with send() and its - * recipient's `idempotency_key`. Shared content over 4 MiB of JSON throws `content_too_large` before any - * request, and a recipient whose email alone is that large is `failed` with `content_too_large`. + * When PostHog refuses the batch as a whole, such as a rate limit past its retries, batch() throws + * EmailBatchError, whose getResults() holds every recipient: `failed`, or `unconfirmed` when an attempt may have + * queued it. The code `too_large` (413) means the batch is larger than PostHog takes: split the recipients into + * smaller batches. `batch_unavailable` (409) means the project can't send batches yet, and is never retried. + * `not_found` (404) means the template doesn't exist or batch sends are off for the project. For both, send each + * email the batch didn't queue with send() and its recipient's `idempotency_key`. * * ```php * $result = $client->emails()->batch([ @@ -483,9 +481,8 @@ public function get(string $messageId): EmailStatus * capture_engagement?: bool|null * } $batch * @return SendBatchResult A result per recipient, in the order of `recipients`. - * @throws EmailBatchError A request failed as a whole, so the batch stopped. getResults() holds every - * recipient, those not sent as `not_attempted`. The code `client_closed` means the client shut down during - * the batch. + * @throws EmailBatchError PostHog refused the batch as a whole, its answer was lost past the retries, or the + * client shut down before a retry (`client_closed`). getResults() holds every recipient. * @throws EmailError The client sent nothing: an argument check failed, with the name `validation_error` and * an `invalid_*` code, such as two recipients with the same `idempotency_key`, or the client can't send, * such as when it is disabled. @@ -1142,32 +1139,21 @@ private function sendBatch(EmailBatch $run, string $appHost, string $secretKey, $timeoutMs = max($this->requestTimeoutMs, self::BATCH_REQUEST_TIMEOUT_MS); $closedBeforeARetry = new EmailError( 'client_closed', - "The PostHog client is shut down, so it didn't retry this request of the batch." + "The PostHog client is shut down, so it didn't retry the batch." ); $url = $appHost . self::BATCH_PATH; - for ($position = 0; $position < $run->requestCount(); $position++) { - if ($position > 0 && ($this->isClosed)()) { - throw $run->failure($run->closedAt($position)); - } - $body = $run->requestBody($position); - $attemptOnce = function () use ($run, $position, $url, $headers, $body, $timeoutMs): void { + $body = $run->requestBody(); + try { + $this->withRetries($maxRetries, function () use ($run, $url, $headers, $body, $timeoutMs): void { try { $reply = $this->request('POST', $url, $headers, $body, $timeoutMs); } catch (EmailError $error) { - if (in_array($error->getErrorCode(), self::LOST_ANSWER_CODES, true)) { - $run->lost($position, $error); - } - throw $error; + throw in_array($error->getErrorCode(), self::LOST_ANSWER_CODES, true) ? $run->lost($error) : $error; } - $run->answer($position, ...$reply); - }; - try { - $this->withRetries($maxRetries, $attemptOnce, $closedBeforeARetry); - } catch (EmailError $error) { - $run->stop($position, $error); - throw $run->failure($error); - } - unset($body, $attemptOnce); + $run->answer(...$reply); + }, $closedBeforeARetry); + } catch (EmailError $error) { + throw $run->failure($error); } } diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index 7e75d45..8b7768a 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -15,8 +15,7 @@ */ final class EmailBatch { - private const MAX_RECIPIENTS_PER_REQUEST = 100; - private const MAX_REQUEST_BYTES = 4 * 1024 * 1024; + private const MAX_RECIPIENTS = 100; private const RECIPIENT_FIELDS = ['to', 'distinct_id', 'idempotency_key', 'template_data']; private const UNCONFIRMED_CODES = ['idempotency_key_in_flight', 'delivery_unavailable', 'api_error']; private const SEND_AGAIN = 'Send it again with the same idempotency_key within 24 hours, so it goes out once.'; @@ -25,20 +24,18 @@ final class EmailBatch private const SEND_SINGLY = "send each email the batch didn't queue with emails()->send() and its recipient's " . 'idempotency_key.'; - /** @var list> The positions in `recipients` that each request carries. */ - private array $requests = []; /** @var array */ private array $results = []; /** @var list */ private array $warnings = []; + private bool $mayHaveQueued = false; /** - * @param list $members + * @param list $members * @param string $opening The request body up to its first recipient. */ private function __construct(private array $members, private string $opening) { - $this->split(); } /** @@ -54,6 +51,14 @@ public static function prepare(array $shared, mixed $recipients): self field: 'recipients' ); } + if (count($recipients) > self::MAX_RECIPIENTS) { + throw new EmailError( + 'invalid_recipients', + 'recipients takes at most ' . self::MAX_RECIPIENTS . ' recipients, so no email was sent.', + fix: 'Send the recipients in batches of at most ' . self::MAX_RECIPIENTS . '.', + field: 'recipients' + ); + } $isTemplateForm = array_key_exists('template_id', $shared); $members = []; $firstWithKey = []; @@ -71,18 +76,9 @@ public static function prepare(array $shared, mixed $recipients): self } $members[] = $member; } - $encoded = []; - $size = strlen('{"recipients":[]}'); - foreach ($shared as $name => $value) { - $encoded[$name] = self::encode($value, 'The email'); - $size += strlen(self::encode((string) $name, 'The email')) + strlen($encoded[$name]) + strlen(':,'); - } - if ($size > self::MAX_REQUEST_BYTES) { - throw self::sharedTooLarge($encoded); - } $pairs = []; - foreach ($encoded as $name => $json) { - $pairs[] = self::encode((string) $name, 'The email') . ':' . $json; + foreach ($shared as $name => $value) { + $pairs[] = self::encode((string) $name, 'The email') . ':' . self::encode($value, 'The email'); } $opening = '{' . implode(',', [...$pairs, '"recipients":[']); @@ -90,7 +86,7 @@ public static function prepare(array $shared, mixed $recipients): self } /** - * @return array{to: string, key: string, bytes: int, wire: ?string, field: string} + * @return array{to: string, key: string, wire: string} */ private static function member(int $index, mixed $recipient, bool $isTemplateForm): array { @@ -123,24 +119,11 @@ private static function member(int $index, mixed $recipient, bool $isTemplateFor $wire['message_data'] = self::templateData($index, $recipient['template_data'], $isTemplateForm); } $values = []; - $sizes = []; - $bytes = strlen('{}') + count($wire) - 1; foreach ($wire as $name => $value) { $values[$name] = self::encode($value, "recipients[$index]", 511); - $sizes[$name === 'message_data' ? 'template_data' : $name] = strlen($values[$name]); - $bytes += strlen("\"$name\":") + strlen($values[$name]); } - $named = array_intersect_key($sizes, ['distinct_id' => true, 'template_data' => true]); - arsort($named); - $largest = array_key_first($named); - - return [ - 'to' => $to, - 'key' => $wire['idempotency_key'], - 'bytes' => $bytes, - 'wire' => $bytes > self::MAX_REQUEST_BYTES ? null : self::joined($values), - 'field' => $largest === null ? "recipients__$index" : "recipients__{$index}__$largest", - ]; + + return ['to' => $to, 'key' => $wire['idempotency_key'], 'wire' => self::joined($values)]; } /** @@ -193,109 +176,45 @@ private static function encode(mixed $payload, string $what, int $depth = 512): } } - private function split(): void + public function requestBody(): string { - $emptyBytes = strlen($this->opening) + strlen(']}'); - $indices = []; - $bytes = $emptyBytes; - foreach ($this->members as $index => $member) { - $memberBytes = $member['bytes']; - if ($emptyBytes + $memberBytes > self::MAX_REQUEST_BYTES) { - $this->set($index, 'failed', error: self::recipientTooLarge($member['field'])); - continue; - } - $separatorBytes = $indices === [] ? 0 : 1; - $full = count($indices) === self::MAX_RECIPIENTS_PER_REQUEST; - if ($indices !== [] && ($full || $bytes + $separatorBytes + $memberBytes > self::MAX_REQUEST_BYTES)) { - $this->requests[] = $indices; - [$indices, $bytes, $separatorBytes] = [[], $emptyBytes, 0]; - } - $indices[] = $index; - $bytes += $separatorBytes + $memberBytes; - } - if ($indices !== []) { - $this->requests[] = $indices; - } - } - - public function requestCount(): int - { - return count($this->requests); + return $this->opening . implode(',', array_column($this->members, 'wire')) . ']}'; } - public function requestBody(int $position): string + public function lost(EmailError $error): EmailError { - $parts = [$this->opening]; - foreach ($this->requests[$position] as $index) { - $parts[] = $this->members[$index]['wire']; - $parts[] = ','; - } - $parts[count($parts) - 1] = ']}'; - - return implode('', $parts); - } + $this->mayHaveQueued = true; + $cause = $error->getErrorCode() === self::IN_FLIGHT ? self::inFlight($error) : self::unconfirmed(null); + $this->setAll('unconfirmed', $cause); - public function lost(int $position, EmailError $error): void - { - $this->recordLaterError($position, $error); - foreach ($this->requests[$position] as $index) { - if (!$this->isUnconfirmed($index)) { - $cause = $error->getErrorCode() === self::IN_FLIGHT ? self::inFlight($error) : self::unconfirmed(null); - $this->set($index, 'unconfirmed', error: $cause); - } - } + return $error; } /** * @param list $headers */ - public function answer(int $position, int $status, string $body, array $headers): void + public function answer(int $status, string $body, array $headers): void { - $indices = $this->requests[$position]; $fields = EmailReplies::fields($body); if ($status < 200 || $status >= 300) { - $error = self::requestError($fields, $status, $headers, $indices); + $error = self::requestError($fields, $status, $headers); if ($status >= 500 || ($status === 409 && $error->getErrorCode() === self::IN_FLIGHT)) { - $this->lost($position, $error); - } else { - $this->recordLaterError($position, $error); + throw $this->lost($error); } throw $error; } $slots = $fields['results'] ?? null; - if (!is_array($slots) || !array_is_list($slots) || count($slots) !== count($indices)) { - $error = new EmailError( + if (!is_array($slots) || !array_is_list($slots) || count($slots) !== count($this->members)) { + throw $this->lost(new EmailError( 'api_error', 'PostHog answered the batch without a result for each recipient.', $status - ); - $this->lost($position, $error); - throw $error; - } - foreach ($indices as $slot => $index) { - $this->settle($index, is_array($slots[$slot]) ? $slots[$slot] : []); + )); } - foreach (EmailReplies::warnings($fields) as $warning) { - if (!in_array($warning, $this->warnings)) { - $this->warnings[] = $warning; - } - } - } - - private function recordLaterError(int $position, EmailError $error): void - { - foreach ($this->requests[$position] as $index) { - if ($this->isUnconfirmed($index)) { - $earlier = $this->results[$index]; - $this->set( - $index, - 'unconfirmed', - $earlier->getMessageId(), - error: $earlier->getError(), - laterError: $error - ); - } + foreach (array_keys($this->members) as $index) { + $this->settle($index, is_array($slots[$index]) ? $slots[$index] : []); } + $this->warnings = EmailReplies::warnings($fields); } /** @@ -310,48 +229,8 @@ private function settle(int $index, array $slot): void return; } $answer = self::slotError($error, $messageId); - if ($this->isUnconfirmed($index)) { - $earlier = $this->results[$index]; - $messageId ??= $earlier->getMessageId(); - $this->set($index, 'unconfirmed', $messageId, error: $earlier->getError(), laterError: $answer); - } elseif (in_array($answer->getErrorCode(), self::UNCONFIRMED_CODES, true)) { - $this->set($index, 'unconfirmed', $messageId, error: $answer); - } else { - $this->set($index, 'failed', $messageId, error: $answer); - } - } - - public function stop(int $position, EmailError $error): void - { - foreach ($this->requests[$position] as $index) { - if (!$this->isUnconfirmed($index)) { - $this->set($index, 'failed', error: $error); - } - } - $this->skipFrom($position + 1, new EmailError( - 'not_attempted', - 'An earlier request of the batch failed, so the client sent nothing for this recipient.' - )); - } - - public function closedAt(int $position): EmailError - { - $error = new EmailError( - 'client_closed', - "The PostHog client is shut down, so the rest of the batch wasn't sent." - ); - $this->skipFrom($position, $error); - - return $error; - } - - private function skipFrom(int $position, EmailError $error): void - { - foreach (array_slice($this->requests, $position) as $indices) { - foreach ($indices as $index) { - $this->set($index, 'not_attempted', error: $error); - } - } + $status = in_array($answer->getErrorCode(), self::UNCONFIRMED_CODES, true) ? 'unconfirmed' : 'failed'; + $this->set($index, $status, $messageId, error: $answer); } public function result(): SendBatchResult @@ -361,12 +240,18 @@ public function result(): SendBatchResult public function failure(EmailError $error): EmailBatchError { + if (!$this->mayHaveQueued) { + $this->setAll('failed', $error); + } + return new EmailBatchError($error, $this->outcome(), $this->warnings); } - private function isUnconfirmed(int $index): bool + private function setAll(string $status, EmailError $error): void { - return ($this->results[$index] ?? null)?->getStatus() === 'unconfirmed'; + foreach (array_keys($this->members) as $index) { + $this->set($index, $status, error: $error); + } } /** @@ -387,8 +272,7 @@ private function set( string $status, ?string $messageId = null, bool $replayed = false, - ?EmailError $error = null, - ?EmailError $laterError = null + ?EmailError $error = null ): void { $member = $this->members[$index]; $this->results[$index] = new BatchEmailResult( @@ -398,22 +282,17 @@ private function set( $status, $messageId, $replayed, - $error, - $laterError + $error ); } /** * @param array $fields * @param list $headers - * @param list $indices */ - private static function requestError(array $fields, int $status, array $headers, array $indices): EmailError + private static function requestError(array $fields, int $status, array $headers): EmailError { $answered = array_filter($fields, static fn($value): bool => $value !== null); - if (is_string($answered['attr'] ?? null)) { - $answered['attr'] = self::recipientsField($answered['attr'], $indices); - } if ($status === 404) { $answered += [ 'code' => 'not_found', @@ -422,6 +301,9 @@ private static function requestError(array $fields, int $status, array $headers, 'fix' => 'Check template_id, or ' . self::SEND_SINGLY, ]; } + if ($status === 413) { + $answered['fix'] = 'Split the recipients into smaller batches.'; + } if (($answered['code'] ?? null) === 'batch_unavailable') { $answered['fix'] = 'Until batch sends are on for the project, ' . self::SEND_SINGLY; } @@ -429,22 +311,6 @@ private static function requestError(array $fields, int $status, array $headers, return EmailReplies::error($answered, $status, $headers); } - /** - * @param list $indices - */ - private static function recipientsField(string $attr, array $indices): string - { - if (preg_match('/^recipients__([0-9]+)((?:__.*)?)$/sD', $attr, $match) !== 1) { - return $attr; - } - [, $position, $rest] = $match; - if (strlen($position) > strlen((string) count($indices)) || (int) $position >= count($indices)) { - return 'recipients'; - } - - return 'recipients__' . $indices[(int) $position] . $rest; - } - private static function slotError(mixed $error, ?string $messageId): EmailError { if (!is_array($error)) { @@ -488,36 +354,4 @@ private static function inFlight(EmailError $error): EmailError $error ); } - - /** - * @param array $encoded - */ - private static function sharedTooLarge(array $encoded): EmailError - { - $sizes = []; - foreach (array_diff_key($encoded, ['template_id' => true, 'template_key' => true]) as $name => $json) { - $sizes[$name === 'message_data' ? 'template_data' : $name] = strlen($json); - } - arsort($sizes); - $field = (string) array_key_first($sizes); - - return new EmailError( - 'content_too_large', - 'The email every recipient of the batch gets is larger than one batch request takes (4 MiB of JSON), so ' - . "no email was sent. Its largest part is $field.", - fix: "Make $field smaller, such as by linking to images instead of embedding them, or send each email " - . 'with emails()->send().', - field: $field - ); - } - - private static function recipientTooLarge(string $field): EmailError - { - return new EmailError( - 'content_too_large', - "This recipient's email is larger than one batch request takes, so it wasn't sent.", - fix: "Send this recipient's email with emails()->send().", - field: $field - ); - } } diff --git a/lib/SendBatchResult.php b/lib/SendBatchResult.php index e9c3743..5a0d349 100644 --- a/lib/SendBatchResult.php +++ b/lib/SendBatchResult.php @@ -27,7 +27,7 @@ public function getResults(): array } /** - * The warnings PostHog returned about the batch, each once. + * The warnings PostHog returned about the batch. * * @return list */ diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index df530d0..702245b 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -13,8 +13,6 @@ use PostHog\Emails; use PostHog\SendBatchResult; use stdClass; -use JsonSerializable; -use RuntimeException; use Symfony\Component\Clock\Clock; use Symfony\Component\Clock\ClockInterface; use Symfony\Component\Clock\MockClock; @@ -25,7 +23,6 @@ class EmailsBatchTest extends TestCase private const TEMPLATE_ID = '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b'; private const BATCH_URL = 'https://us.posthog.com/api/messaging/send/email_batch/'; - private const FOUR_MIB = 4 * 1024 * 1024; private const UUID_V4 = '/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/D'; private const WARNING_LOGGED = '[PostHog][Emails] Email warning sandbox_sender: Sent from the test sender.'; private const SEND_SINGLY = "send each email the batch didn't queue with emails()->send() and its recipient's " @@ -277,7 +274,6 @@ public function testATemplateBatchPostsOneRequestWithAResultPerRecipient(): void $error->getErrorName(), ] ); - $this->assertNull($results[2]->getLaterError()); $this->assertSame([], $result->getWarnings()); } @@ -435,313 +431,43 @@ public function testNamesThePositionOfABadRecipient(): void $this->assertStringStartsWith('recipients[1]: ', $error->getMessage()); } - public function testSplitsBy100RecipientsAndSendsTheRequestsInOrder(): void + public function testMoreThan100RecipientsAreRefusedBeforeAnyRequest(): void { - $this->reply(self::allQueued(), self::allQueued(), self::allQueued()); - - $result = $this->batch(self::recipients(250)); - - $this->assertSame([100, 100, 50], $this->recipientsPerRequest()); - $results = $result->getResults(); - $this->assertSame(range(0, 249), array_map(static fn($r): int => $r->getIndex(), $results)); - $this->assertSame( - array_map(static fn(int $i): string => "msg_key-$i", range(0, 249)), - array_map(static fn($r): ?string => $r->getMessageId(), $results) - ); - $this->assertSame(self::times(250, 'queued'), self::statuses($results)); - } - - public function testSplitsByThe4MibBodyAndFailsOnlyARecipientTooLargeAlone(): void - { - $recipients = self::recipients(5, ['template_data' => ['note' => str_repeat('x', intdiv(self::FOUR_MIB, 3))]]); - $recipients[3]['template_data'] = ['note' => str_repeat('y', self::FOUR_MIB)]; - $this->reply(self::allQueued(), self::allQueued()); - - $result = $this->batch($recipients); - - foreach ($this->requests as $request) { - $this->assertLessThanOrEqual(self::FOUR_MIB, strlen($request['body'])); - } - $this->assertSame( - [['key-0', 'key-1'], ['key-2', 'key-4']], - array_map( - static fn(array $body): array => array_column($body['recipients'], 'idempotency_key'), - $this->batchBodies() - ) - ); - $results = $result->getResults(); - $this->assertSame(['queued', 'queued', 'queued', 'failed', 'queued'], self::statuses($results)); - $tooLarge = $results[3]; - $this->assertSame(['content_too_large', 'recipients__3__template_data', 'validation_error'], [ - $tooLarge->getError()->getErrorCode(), - $tooLarge->getError()->getField(), - $tooLarge->getError()->getErrorName(), - ]); - $this->assertSame([null, 'key-3'], [$tooLarge->getMessageId(), $tooLarge->getIdempotencyKey()]); - } - - public static function sharedContentOver4Mib(): array - { - $over = str_repeat('x', self::FOUR_MIB); - - return [ - 'html' => [['template_key' => 'news', 'subject' => 'News', 'html' => $over, 'text' => 'Hi'], 'html'], - 'text' => [['template_key' => 'news', 'subject' => 'News', 'html' => '

Hi

', 'text' => $over], 'text'], - 'from' => [['template_key' => 'news', 'subject' => 'News', 'html' => '

Hi

', 'from' => $over], 'from'], - 'reply_to' => [ - ['template_key' => 'news', 'subject' => 'News', 'html' => '

Hi

', 'reply_to' => $over], - 'reply_to', - ], - 'template_data' => [ - ['template_id' => self::TEMPLATE_ID, 'template_data' => ['note' => $over]], - 'template_data', - ], - ]; - } - - #[DataProvider('sharedContentOver4Mib')] - public function testSharedContentOver4MibIsRefusedBeforeAnyRequest(array $content, string $field): void - { - $error = $this->refusal(['recipients' => self::recipients(2), ...$content]); + $error = $this->refusal(['recipients' => self::recipients(101), 'template_id' => self::TEMPLATE_ID]); $this->assertNotInstanceOf(EmailBatchError::class, $error); - $this->assertSame(['content_too_large', $field, 'validation_error'], [ - $error->getErrorCode(), - $error->getField(), - $error->getErrorName(), - ]); - $this->assertSame([], $this->requests); - } - - public function testSharedContentOver4MibOnlyTogetherNamesItsLargestPart(): void - { - $half = intdiv(self::FOUR_MIB, 2) + 1024; - - $error = $this->refusal([ - 'recipients' => self::recipients(1), - 'template_key' => 'news', - 'subject' => 'News', - 'html' => str_repeat('h', $half + 1), - 'text' => str_repeat('t', $half), - ]); - - $this->assertSame([ - 'content_too_large', - 'html', - 'The email every recipient of the batch gets is larger than one batch request takes (4 MiB of JSON), so ' - . 'no email was sent. Its largest part is html.', - ], [$error->getErrorCode(), $error->getField(), $error->getMessage()]); - $this->assertSame([], $this->requests); - } - - public static function recipientsTooLargeAlone(): array - { - return [ - 'a large distinct_id' => [self::FOUR_MIB, 2, 'recipients__0__distinct_id'], - 'large template_data' => [6, self::FOUR_MIB, 'recipients__0__template_data'], - 'a distinct_id a little larger than template_data' => [2097130, 2097115, 'recipients__0__distinct_id'], - 'template_data a little larger than distinct_id' => [2097115, 2097130, 'recipients__0__template_data'], - ]; - } - - #[DataProvider('recipientsTooLargeAlone')] - public function testARecipientTooLargeAloneNamesItsLargestField( - int $distinctIdBytes, - int $noteBytes, - string $field - ): void { - $result = $this->batch([[ - 'to' => 'a@example.com', - 'idempotency_key' => 'k1', - 'distinct_id' => str_repeat('d', $distinctIdBytes), - 'template_data' => ['x' => str_repeat('x', $noteBytes)], - ]]); - - $recipient = $result->getResults()[0]; $this->assertSame( - ['failed', 'content_too_large', $field], - [$recipient->getStatus(), $recipient->getError()->getErrorCode(), $recipient->getError()->getField()] + ['invalid_recipients', 'recipients', 'validation_error'], + [$error->getErrorCode(), $error->getField(), $error->getErrorName()] ); + $this->assertSame('recipients takes at most 100 recipients, so no email was sent.', $error->getMessage()); $this->assertSame([], $this->requests); } - public static function sharedContentAtTheLimit(): array - { - return [ - 'exactly 4 MiB' => [0, 'recipient failed with content_too_large'], - 'one byte more' => [1, 'batch throws content_too_large for template_data'], - ]; - } - - #[DataProvider('sharedContentAtTheLimit')] - public function testSharedContentTakesUpToExactly4MibOfRequest(int $bytesOver, string $outcome): void - { - $empty = ['template_id' => self::TEMPLATE_ID, 'message_data' => ['n' => ''], 'recipients' => []]; - $note = str_repeat('a', self::FOUR_MIB - strlen(json_encode($empty)) + $bytesOver); - - try { - $result = $this->batch(self::recipients(1), ['template_data' => ['n' => $note]]); - $recipient = $result->getResults()[0]; - $actual = "recipient {$recipient->getStatus()} with {$recipient->getError()->getErrorCode()}"; - } catch (EmailError $error) { - $actual = "batch throws {$error->getErrorCode()} for {$error->getField()}"; - } - - $this->assertSame([$outcome, []], [$actual, $this->requests]); - } - - public static function valuesThatChangeOnASecondEncoding(): array - { - return [ - 'INF the second time' => [static fn(): float => INF], - 'an exception the second time' => [static function (): never { - throw new RuntimeException('Serialized twice.'); - }], - ]; - } - - #[DataProvider('valuesThatChangeOnASecondEncoding')] - public function testSharedContentOver4MibIsDiagnosedFromItsOnlyEncoding(Closure $secondTime): void + public function testABatchTooLargeForPostHogIsTheErrorAndSaysToSplitIt(): void { - $note = new class (str_repeat('x', self::FOUR_MIB), $secondTime) implements JsonSerializable { - private int $encodings = 0; - - public function __construct(private string $first, private Closure $secondTime) - { - } + $this->reply(self::wholeCall(413, 'too_large')); - public function jsonSerialize(): mixed - { - return $this->encodings++ === 0 ? $this->first : ($this->secondTime)(); - } - }; + $error = $this->batchError(self::recipients(100), ['max_retries' => 2]); - $error = $this->refusal([ - 'recipients' => self::recipients(1), - 'template_id' => self::TEMPLATE_ID, - 'template_data' => ['note' => $note], + $this->assertSame(['too_large', 413, 'Nope.'], [ + $error->getErrorCode(), + $error->getStatusCode(), + $error->getMessage(), ]); - - $this->assertSame(['content_too_large', 'template_data'], [$error->getErrorCode(), $error->getField()]); - $this->assertSame([], $this->requests); - } - - public function testABatchOf10000RecipientsFitsIn24MibOfMemory(): void - { - $script = <<<'PHP' - 'msg_' . $recipient['idempotency_key'], 'status' => 'queued']; - } - - return [200, json_encode(['results' => $slots]), []]; -}); -$recipients = []; -for ($index = 0; $index < 10000; $index++) { - $recipients[] = ['to' => "user$index@example.com", 'idempotency_key' => "key-$index"]; -} -$result = $emails->batch([ - 'recipients' => $recipients, - 'template_id' => '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b', - 'template_data' => ['note' => str_repeat('x', 150000)], -]); -$queued = count(array_filter($result->getResults(), static fn($email): bool => $email->getStatus() === 'queued')); -echo json_encode([$requests, $queued]); -PHP; - $this->assertSame([0, '[100,10000]'], self::runWithMemoryLimit($script, '24M')); - } - - public function testARecipientWithA10MibDistinctIdOfNulBytesFailsWithin128MibOfMemory(): void - { - $script = <<<'PHP' - [500, '', []]); -$recipient = $emails->batch([ - 'recipients' => [['to' => 'user@example.com', 'distinct_id' => str_repeat("\0", 10 * 1024 * 1024)]], - 'template_id' => '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b', -])->getResults()[0]; -echo json_encode([$recipient->getStatus(), $recipient->getError()->getErrorCode(), $recipient->getError()->getField()]); -PHP; - $this->assertSame( - [0, '["failed","content_too_large","recipients__0__distinct_id"]'], - self::runWithMemoryLimit($script, '128M') - ); - } - - public function testA32MibHtmlIsRefusedWithin128MibOfMemory(): void - { - $script = <<<'PHP' -batch([ - 'recipients' => [['to' => 'user@example.com']], - 'template_key' => 'news', - 'subject' => 'News', - 'html' => str_repeat('x', 32 * 1024 * 1024), - ]); -} catch (PostHog\EmailError $error) { - echo json_encode([$requests, $error->getErrorCode(), $error->getField()]); -} -PHP; - $this->assertSame([0, '[0,"content_too_large","html"]'], self::runWithMemoryLimit($script, '128M')); + $this->assertSame('Split the recipients into smaller batches.', $error->getFix()); + $this->assertSame(self::times(100, 'failed'), self::statuses($error->getResults())); + $this->assertCount(1, $this->requests); } - public function testEachRequestOfABatchIsBuiltAfterThePreviousOneIsFreed(): void + public function testAHundredRecipientsGoOutInOneRequest(): void { - $script = <<<'PHP' - "msg_$key", 'status' => 'queued']; - } + $this->reply(self::allQueued()); - return [200, json_encode(['results' => $slots]), []]; -}); -$recipients = []; -for ($index = 0; $index < 8; $index++) { - $recipients[] = [ - 'to' => "user$index@example.com", - 'idempotency_key' => "key-$index", - 'template_data' => ['note' => str_repeat(chr(97 + $index), 1010000)], - ]; -} -$result = $emails->batch(['recipients' => $recipients, 'template_id' => '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b']); -$queued = count(array_filter($result->getResults(), static fn($email): bool => $email->getStatus() === 'queued')); -echo json_encode([$requests, $queued]); -PHP; + $result = $this->batch(self::recipients(100)); - $this->assertSame([0, '[2,8]'], self::runWithMemoryLimit($script, '29M')); + $this->assertSame([100], $this->recipientsPerRequest()); + $this->assertSame(self::times(100, 'queued'), self::statuses($result->getResults())); } public function testARecipientIsEncodedWithoutExtraCopiesOfItsData(): void @@ -823,34 +549,6 @@ private static function runWithMemoryLimit(string $code, string $limit): array } } - public static function requestsAtTheLimit(): array - { - return [ - 'exactly 4 MiB' => [0, [3]], - 'one byte more' => [1, [2, 1]], - ]; - } - - #[DataProvider('requestsAtTheLimit')] - public function testARequestTakesRecipientsUpToExactly4Mib(int $bytesOver, array $recipientsPerRequest): void - { - $empty = ['template_id' => self::TEMPLATE_ID, 'message_data' => new stdClass(), 'recipients' => []]; - $base = strlen(json_encode($empty)); - $recipient = ['to' => 'a@example.com', 'idempotency_key' => 'k1', 'message_data' => ['n' => '']]; - $item = strlen(json_encode($recipient)); - $recipient = ['to' => 'a@example.com', 'idempotency_key' => 'k1', 'template_data' => ['n' => '']]; - $note = str_repeat('a', self::FOUR_MIB - $base - 3 * $item - 2 + $bytesOver); - $this->reply(...array_fill(0, count($recipientsPerRequest), self::allQueued())); - - $this->batch([ - [...$recipient, 'template_data' => ['n' => $note]], - [...$recipient, 'idempotency_key' => 'k2'], - [...$recipient, 'idempotency_key' => 'k3'], - ]); - - $this->assertSame($recipientsPerRequest, $this->recipientsPerRequest()); - } - public function testABatchWaitsForASlowAnswerWhateverTheClientTimeout(): void { $this->reply(self::slow(40, self::allQueued())); @@ -869,7 +567,7 @@ public function testALongerClientTimeoutAppliesToABatchToo(): void $this->assertSame(['queued'], self::statuses($result->getResults())); } - public function testARetryAfterALostAnswerKeepsARefusedRecipientUnconfirmed(): void + public function testARetryAfterALostAnswerReportsWhatTheRetryAnswered(): void { $this->reply( self::networkError(), @@ -887,10 +585,8 @@ public function testARetryAfterALostAnswerKeepsARefusedRecipientUnconfirmed(): v [$first, $second] = $result->getResults(); $this->assertSame($derived, $second->getIdempotencyKey()); $this->assertSame(['queued', 'm0', true], [$first->getStatus(), $first->getMessageId(), $first->isReplayed()]); - $this->assertSame(['unconfirmed', 'm1'], [$second->getStatus(), $second->getMessageId()]); - $this->assertSame('delivery_unavailable', $second->getError()->getErrorCode()); - $this->assertSame('service_unavailable', $second->getError()->getErrorName()); - $this->assertSame('idempotency_key_reused', $second->getLaterError()->getErrorCode()); + $this->assertSame(['failed', 'm1'], [$second->getStatus(), $second->getMessageId()]); + $this->assertSame('idempotency_key_reused', $second->getError()->getErrorCode()); } public function testAnAnswerTooLargeToReadLeavesTheRequestUnconfirmed(): void @@ -916,7 +612,6 @@ public function testA503ThenARefusalOfTheWholeRequestKeepsTheRecipientUnconfirme [$result] = $error->getResults(); $this->assertSame('unconfirmed', $result->getStatus()); $this->assertSame('delivery_unavailable', $result->getError()->getErrorCode()); - $this->assertSame('sending_paused', $result->getLaterError()->getErrorCode()); } public function testARecipientThePipelineDidNotConfirmIsUnconfirmed(): void @@ -930,7 +625,6 @@ public function testARecipientThePipelineDidNotConfirmIsUnconfirmed(): void $result->getError()->getErrorCode(), $result->getError()->getStatusCode(), ]); - $this->assertNull($result->getLaterError()); $this->assertSame('key-0', $result->getIdempotencyKey()); } @@ -958,11 +652,8 @@ public function testAWholeRequestInFlightAnswerLeavesItsRecipientsUnconfirmed(): $this->assertSame('idempotency_key_in_flight', $error->getErrorCode()); $this->assertSame( - [['unconfirmed', null, null], ['unconfirmed', null, null]], - array_map( - static fn($r): array => [$r->getStatus(), $r->getMessageId(), $r->getLaterError()], - $error->getResults() - ) + [['unconfirmed', null], ['unconfirmed', null]], + array_map(static fn($r): array => [$r->getStatus(), $r->getMessageId()], $error->getResults()) ); $recipientError = $error->getResults()[0]->getError(); $this->assertSame( @@ -981,53 +672,29 @@ public static function attemptsAfterAnInFlightAnswer(): array return [ 'a refusal after an in-flight answer' => [ [self::wholeCall(409, 'idempotency_key_in_flight'), self::wholeCall(429, 'quota_limited')], - 'idempotency_key_in_flight', 'quota_limited', ], 'an in-flight answer after a 503' => [ [self::wholeCall(503, 'delivery_unavailable'), self::wholeCall(409, 'idempotency_key_in_flight')], - 'delivery_unavailable', 'idempotency_key_in_flight', ], ]; } #[DataProvider('attemptsAfterAnInFlightAnswer')] - public function testTheAttemptAfterTheOneThatLeftARecipientUnconfirmedIsItsLaterError( + public function testAnAttemptThatMayHaveQueuedKeepsItsRecipientsUnconfirmedWhateverTheNextAnswers( array $answers, - string $code, - string $laterCode + string $code ): void { $this->reply(...$answers); $error = $this->batchError(self::recipients(1), ['max_retries' => 1]); - [$result] = $error->getResults(); - $this->assertSame('unconfirmed', $result->getStatus()); - $this->assertSame($code, $result->getError()->getErrorCode()); - $this->assertSame($laterCode, $result->getLaterError()->getErrorCode()); + $this->assertSame($code, $error->getErrorCode()); + $this->assertSame(['unconfirmed'], self::statuses($error->getResults())); $this->assertSame([self::BATCH_URL, self::BATCH_URL], $this->requestUrls()); } - public function testAShutdownDuringABatchStopsItBeforeTheNextRequest(): void - { - $this->reply(function (string $url, string $body): array { - $this->closed = true; - - return self::allQueued()($url, $body); - }, self::allQueued()); - - $error = $this->batchError(self::recipients(150), emails: $this->closedEmails()); - - $this->assertSame('client_closed', $error->getErrorCode()); - $this->assertCount(1, $this->requests); - $this->assertSame( - [...self::times(100, 'queued'), ...self::times(50, 'not_attempted')], - self::statuses($error->getResults()) - ); - $this->assertSame('client_closed', $error->getResults()[100]->getError()->getErrorCode()); - } - public function testAShutdownDuringARetryWaitSendsNoRetry(): void { Clock::set(self::clockThatShutsDownOnSleep($this->clock, function (): void { @@ -1035,14 +702,11 @@ public function testAShutdownDuringARetryWaitSendsNoRetry(): void })); $this->reply(self::wholeCall(429), self::allQueued()); - $error = $this->batchError(self::recipients(150), emails: $this->closedEmails()); + $error = $this->batchError(self::recipients(2), emails: $this->closedEmails()); $this->assertSame('client_closed', $error->getErrorCode()); $this->assertCount(1, $this->requests); - $this->assertSame( - [...self::times(100, 'failed'), ...self::times(50, 'not_attempted')], - self::statuses($error->getResults()) - ); + $this->assertSame(['failed', 'failed'], self::statuses($error->getResults())); $this->assertSame('client_closed', $error->getResults()[0]->getError()->getErrorCode()); } @@ -1071,29 +735,21 @@ public function withTimeZone(DateTimeZone|string $timezone): static }; } - public function testARequestRefusedAsAWholeThrowsWithTheResultsSoFar(): void + public function testARequestRefusedAsAWholeThrowsWithEveryRecipient(): void { - $this->reply(self::allQueued(), self::wholeCall(429, 'quota_limited')); + $this->reply(self::wholeCall(429, 'quota_limited')); - $error = $this->batchError(self::recipients(250)); + $error = $this->batchError(self::recipients(3)); - $this->assertInstanceOf(EmailError::class, $error); $this->assertSame( ['quota_limited', 429, 'Nope.'], [$error->getErrorCode(), $error->getStatusCode(), $error->getMessage()] ); - $this->assertCount(2, $this->requests); + $this->assertCount(1, $this->requests); $results = $error->getResults(); - $this->assertSame( - [...self::times(100, 'queued'), ...self::times(100, 'failed'), ...self::times(50, 'not_attempted')], - self::statuses($results) - ); - $this->assertSame(['quota_limited', 'Nope.'], [ - $results[150]->getError()->getErrorCode(), - $results[150]->getError()->getMessage(), - ]); - $this->assertSame('not_attempted', $results[200]->getError()->getErrorCode()); - $this->assertSame('key-249', $results[249]->getIdempotencyKey()); + $this->assertSame(self::times(3, 'failed'), self::statuses($results)); + $this->assertSame('quota_limited', $results[1]->getError()->getErrorCode()); + $this->assertSame('key-2', $results[2]->getIdempotencyKey()); } public function testARefusalOfTheWholeRequestAfterALostAnswerKeepsItsRecipientsUnconfirmed(): void @@ -1105,7 +761,6 @@ public function testARefusalOfTheWholeRequestAfterALostAnswerKeepsItsRecipientsU [$result] = $error->getResults(); $this->assertSame(['unconfirmed', null], [$result->getStatus(), $result->getMessageId()]); $this->assertSame('delivery_unavailable', $result->getError()->getErrorCode()); - $this->assertSame('quota_limited', $result->getLaterError()->getErrorCode()); $this->assertSame([self::BATCH_URL, self::BATCH_URL], $this->requestUrls()); } @@ -1188,33 +843,20 @@ public static function retriesAfterAnUnconfirmingAttempt(): array ]; } - public function testARetryThatLosesItsAnswerAgainIsTheLaterError(): void - { - $this->reply(self::networkError(), self::networkError()); - - $error = $this->batchError(self::recipients(1), ['max_retries' => 1]); - - $this->assertSame('network_error', $error->getErrorCode()); - [$result] = $error->getResults(); - $this->assertSame([2, 'unconfirmed'], [count($this->batchBodies()), $result->getStatus()]); - $this->assertSame('delivery_unavailable', $result->getError()->getErrorCode()); - $this->assertSame('network_error', $result->getLaterError()?->getErrorCode()); - } - #[DataProvider('retriesAfterAnUnconfirmingAttempt')] - public function testARetryThatCannotConfirmEitherIsTheLaterError( + public function testARetryThatCannotConfirmEitherLeavesTheRecipientUnconfirmed( mixed $first, mixed $retry, - string $laterCode + string $code ): void { $this->reply($first, $retry); $error = $this->batchError(self::recipients(1), ['max_retries' => 1]); + $this->assertSame($code, $error->getErrorCode()); [$result] = $error->getResults(); $this->assertSame('unconfirmed', $result->getStatus()); $this->assertSame('delivery_unavailable', $result->getError()->getErrorCode()); - $this->assertSame($laterCode, $result->getLaterError()?->getErrorCode()); } public function testAnAnswerWithoutAResultPerRecipientLeavesTheRequestUnconfirmed(): void @@ -1225,10 +867,6 @@ public function testAnAnswerWithoutAResultPerRecipientLeavesTheRequestUnconfirme $this->assertSame('api_error', $error->getErrorCode()); $this->assertSame(['unconfirmed', 'unconfirmed'], self::statuses($error->getResults())); - $this->assertSame( - [null, null], - array_map(static fn($r): ?EmailError => $r->getLaterError(), $error->getResults()) - ); $this->assertSame([self::BATCH_URL], $this->requestUrls()); } @@ -1236,27 +874,15 @@ public function testWarningsReachTheCallerOnce(): void { global $errorMessages; $warning = ['code' => 'sandbox_sender', 'detail' => 'Sent from the test sender.']; - $this->reply(self::allQueued(['warnings' => [$warning]]), self::allQueued(['warnings' => [$warning]])); + $this->reply(self::allQueued(['warnings' => [$warning]])); - $result = $this->batch(self::recipients(150)); + $result = $this->batch(self::recipients(2)); $codes = array_map(static fn($warning): string => $warning->getCode(), $result->getWarnings()); $this->assertSame(['sandbox_sender'], $codes); $this->assertSame([self::WARNING_LOGGED], $errorMessages); } - public function testWarningsReachTheCallerWhenALaterRequestFails(): void - { - global $errorMessages; - $warning = ['code' => 'sandbox_sender', 'detail' => 'Sent from the test sender.']; - $this->reply(self::allQueued(['warnings' => [$warning]]), self::wholeCall(429, 'quota_limited')); - - $error = $this->batchError(self::recipients(150)); - - $this->assertSame(['sandbox_sender'], array_map(static fn($w): string => $w->getCode(), $error->getWarnings())); - $this->assertSame([self::WARNING_LOGGED], $errorMessages); - } - public static function setupErrors(): array { return [ @@ -1279,35 +905,4 @@ public function testAClientThatCannotSendSendsNothing(array $config, string $cod $this->assertSame($code, $error->getErrorCode()); $this->assertSame([], $this->requests); } - - public static function refusedRecipientFields(): array - { - return [ - 'a position in the request' => ['recipients__37__idempotency_key', 'recipients__137__idempotency_key'], - 'a position alone' => ['recipients__37', 'recipients__137'], - 'not an ASCII number' => ["recipients__\u{00b2}__idempotency_key", "recipients__\u{00b2}__idempotency_key"], - 'past the request' => ['recipients__50__to', 'recipients'], - 'a huge number' => ['recipients__' . str_repeat('9', 5000) . '__idempotency_key', 'recipients'], - 'another field' => ['template_id', 'template_id'], - ]; - } - - #[DataProvider('refusedRecipientFields')] - public function testARefusedRecipientFieldNamesItsPositionInRecipients(string $attr, string $field): void - { - $this->reply(self::allQueued(), [400, json_encode([ - 'type' => 'validation_error', - 'code' => 'max_length', - 'detail' => 'Ensure this field has no more than 255 characters.', - 'attr' => $attr, - ]), []]); - - $error = $this->batchError(self::recipients(150)); - - $this->assertSame($field, $error->getField()); - $this->assertSame( - [...self::times(100, 'queued'), ...self::times(50, 'failed')], - self::statuses($error->getResults()) - ); - } } From de527e6ad1413a1f4a4580602bcdd482761713d6 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:43:28 +0100 Subject: [PATCH 24/44] docs(emails): name PostHog's 413 code content_too_large for batches Co-Authored-By: Claude Opus 5.5 --- .changeset/email-batch-sends.md | 2 +- README.md | 2 +- lib/Emails.php | 5 +++-- test/EmailsBatchTest.php | 4 ++-- 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/.changeset/email-batch-sends.md b/.changeset/email-batch-sends.md index aca9826..e1ff874 100644 --- a/.changeset/email-batch-sends.md +++ b/.changeset/email-batch-sends.md @@ -2,4 +2,4 @@ "posthog-php": minor --- -Transactional email: `emails()->batch()` sends the same email to many recipients, one email each, from a template with `template_data` per recipient or from content in your code. A call takes up to 100 recipients and sends one request. The client gives each recipient an idempotency key that every retry reuses, and returns a `SendBatchResult` with a `BatchEmailResult` per recipient: `queued`, `failed` or `unconfirmed`. A batch PostHog refuses as a whole, such as `too_large`, throws `EmailBatchError` with every recipient's result. +Transactional email: `emails()->batch()` sends the same email to many recipients, one email each, from a template with `template_data` per recipient or from content in your code. A call takes up to 100 recipients and sends one request. The client gives each recipient an idempotency key that every retry reuses, and returns a `SendBatchResult` with a `BatchEmailResult` per recipient: `queued`, `failed` or `unconfirmed`. A batch PostHog refuses as a whole, such as `content_too_large`, throws `EmailBatchError` with every recipient's result. diff --git a/README.md b/README.md index 555e6af..0a11283 100644 --- a/README.md +++ b/README.md @@ -109,7 +109,7 @@ foreach ($result->getResults() as $email) { - **Requests.** A batch takes 1 to 100 recipients and goes out in one request. The client waits at least 45 seconds for the answer. More than 100 recipients throws `invalid_recipients` before any request. - **Idempotency keys.** Every retry reuses each recipient's key, so a retry never queues an email twice. Without a key, the client makes one that covers its own retries but not a second call. When a batch may be cut off and run again, pass keys you store: send it again with the same key within 24 hours, so it goes out once. Each recipient of a call needs a different key. Build each key from an ID you store with the job, such as the digest's own ID, never from the time of the run: a retry after midnight would make new keys and send the emails again. Never reuse a key for another email: PostHog sends one email per key, so the other doesn't go out. PostHog usually refuses it with `idempotency_key_reused`, but two sends that arrive at the same time can both answer `queued`. - **Statuses.** `getStatus()` is `queued` when PostHog accepted the email, `failed` when it refused it (`getError()` says why, such as a suppressed address), and `unconfirmed` when the client can't tell, such as after a lost answer. Send each `unconfirmed` email again with the same key within 24 hours, so it goes out once. `getWarnings()` holds PostHog's warnings. -- **Errors.** When PostHog refuses the batch as a whole, such as a rate limit past its retries, `batch()` throws `PostHog\EmailBatchError`, whose `getResults()` holds every recipient. `too_large` (413) means the batch is larger than PostHog takes: split the recipients into smaller batches. `batch_unavailable` (409) means the project can't send batches yet, and is never retried. `not_found` (404) means the template doesn't exist or batch sends are off. For both, send each email the batch didn't queue with `send()` and its recipient's `idempotency_key`. +- **Errors.** When PostHog refuses the batch as a whole, such as a rate limit past its retries, `batch()` throws `PostHog\EmailBatchError`, whose `getResults()` holds every recipient. `content_too_large` (413) means the batch is larger than PostHog takes: split the recipients into smaller batches. `batch_unavailable` (409) means the project can't send batches yet, and is never retried. `not_found` (404) means the template doesn't exist or batch sends are off. For both, send each email the batch didn't queue with `send()` and its recipient's `idempotency_key`. ## Questions? diff --git a/lib/Emails.php b/lib/Emails.php index f214094..689ed81 100644 --- a/lib/Emails.php +++ b/lib/Emails.php @@ -436,8 +436,9 @@ public function get(string $messageId): EmailStatus * * When PostHog refuses the batch as a whole, such as a rate limit past its retries, batch() throws * EmailBatchError, whose getResults() holds every recipient: `failed`, or `unconfirmed` when an attempt may have - * queued it. The code `too_large` (413) means the batch is larger than PostHog takes: split the recipients into - * smaller batches. `batch_unavailable` (409) means the project can't send batches yet, and is never retried. + * queued it. The code `content_too_large` (413) means the batch is larger than PostHog takes: split the + * recipients into smaller batches. `batch_unavailable` (409) means the project can't send batches yet, and is + * never retried. * `not_found` (404) means the template doesn't exist or batch sends are off for the project. For both, send each * email the batch didn't queue with send() and its recipient's `idempotency_key`. * diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index 702245b..803f95e 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -446,11 +446,11 @@ public function testMoreThan100RecipientsAreRefusedBeforeAnyRequest(): void public function testABatchTooLargeForPostHogIsTheErrorAndSaysToSplitIt(): void { - $this->reply(self::wholeCall(413, 'too_large')); + $this->reply(self::wholeCall(413, 'content_too_large')); $error = $this->batchError(self::recipients(100), ['max_retries' => 2]); - $this->assertSame(['too_large', 413, 'Nope.'], [ + $this->assertSame(['content_too_large', 413, 'Nope.'], [ $error->getErrorCode(), $error->getStatusCode(), $error->getMessage(), From 42228fc0bb587eb3f20e69a8fd2612a1bfcb9ec2 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:45:36 +0100 Subject: [PATCH 25/44] fix(emails): claim a batch key in flight only on a 409 Co-Authored-By: Claude Opus 5.5 --- lib/Internal/EmailBatch.php | 3 ++- test/EmailsBatchTest.php | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index 8b7768a..824abee 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -184,7 +184,8 @@ public function requestBody(): string public function lost(EmailError $error): EmailError { $this->mayHaveQueued = true; - $cause = $error->getErrorCode() === self::IN_FLIGHT ? self::inFlight($error) : self::unconfirmed(null); + $inFlight = $error->getStatusCode() === 409 && $error->getErrorCode() === self::IN_FLIGHT; + $cause = $inFlight ? self::inFlight($error) : self::unconfirmed(null); $this->setAll('unconfirmed', $cause); return $error; diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index 803f95e..1855999 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -786,6 +786,19 @@ public function testALostAnswerAfterTheRetriesTellsEachRecipientToSendAgainWithI ); } + public function testAnInFlightCodeOnA503LeavesItsRecipientsUnconfirmedWithoutClaimingTheKeyIsInFlight(): void + { + $this->reply(self::wholeCall(503, 'idempotency_key_in_flight')); + + $error = $this->batchError(self::recipients(1), ['max_retries' => 0]); + + [$result] = $error->getResults(); + $this->assertSame(['unconfirmed', 'delivery_unavailable'], [ + $result->getStatus(), + $result->getError()->getErrorCode(), + ]); + } + public function testAnInFlightCodeOnAnAnswerOtherThanA409RefusesTheRequest(): void { $this->reply(self::wholeCall(400, 'idempotency_key_in_flight')); From 59410803a200ce690da0263235a519f9c9ef6e4e Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:10:37 +0100 Subject: [PATCH 26/44] fix(emails): keep retried batch recipients unconfirmed, build body once - A recipient a retry refuses after a lost answer stays unconfirmed with the same-key resend advice, since the first attempt may have queued it. - A 413 keeps PostHog's own fix. Without one, the advice covers a smaller email as well as fewer recipients. A 400 content_too_large gets no split advice. - The request body is encoded once and grown in place, so a batch near PostHog's body limit no longer runs out of PHP memory first. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- lib/Emails.php | 7 +-- lib/Internal/EmailBatch.php | 36 ++++++++----- test/EmailsBatchTest.php | 103 ++++++++++++++++++++++++++++++++---- 4 files changed, 122 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 0a11283..cb3bd92 100644 --- a/README.md +++ b/README.md @@ -109,7 +109,7 @@ foreach ($result->getResults() as $email) { - **Requests.** A batch takes 1 to 100 recipients and goes out in one request. The client waits at least 45 seconds for the answer. More than 100 recipients throws `invalid_recipients` before any request. - **Idempotency keys.** Every retry reuses each recipient's key, so a retry never queues an email twice. Without a key, the client makes one that covers its own retries but not a second call. When a batch may be cut off and run again, pass keys you store: send it again with the same key within 24 hours, so it goes out once. Each recipient of a call needs a different key. Build each key from an ID you store with the job, such as the digest's own ID, never from the time of the run: a retry after midnight would make new keys and send the emails again. Never reuse a key for another email: PostHog sends one email per key, so the other doesn't go out. PostHog usually refuses it with `idempotency_key_reused`, but two sends that arrive at the same time can both answer `queued`. - **Statuses.** `getStatus()` is `queued` when PostHog accepted the email, `failed` when it refused it (`getError()` says why, such as a suppressed address), and `unconfirmed` when the client can't tell, such as after a lost answer. Send each `unconfirmed` email again with the same key within 24 hours, so it goes out once. `getWarnings()` holds PostHog's warnings. -- **Errors.** When PostHog refuses the batch as a whole, such as a rate limit past its retries, `batch()` throws `PostHog\EmailBatchError`, whose `getResults()` holds every recipient. `content_too_large` (413) means the batch is larger than PostHog takes: split the recipients into smaller batches. `batch_unavailable` (409) means the project can't send batches yet, and is never retried. `not_found` (404) means the template doesn't exist or batch sends are off. For both, send each email the batch didn't queue with `send()` and its recipient's `idempotency_key`. +- **Errors.** When PostHog refuses the batch as a whole, such as a rate limit past its retries, `batch()` throws `PostHog\EmailBatchError`, whose `getResults()` holds every recipient. `getFix()` carries PostHog's advice. `content_too_large` with status 413 means the request is larger than PostHog takes: send fewer recipients in each batch, or a smaller email. With status 400 it means the shared content is too large, so fewer recipients won't help: make the content or `template_data` smaller. `batch_unavailable` (409) means the project can't send batches yet, and is never retried. `not_found` (404) means the template doesn't exist or batch sends are off. For both, send each email the batch didn't queue with `send()` and its recipient's `idempotency_key`. ## Questions? diff --git a/lib/Emails.php b/lib/Emails.php index 689ed81..2201906 100644 --- a/lib/Emails.php +++ b/lib/Emails.php @@ -436,9 +436,10 @@ public function get(string $messageId): EmailStatus * * When PostHog refuses the batch as a whole, such as a rate limit past its retries, batch() throws * EmailBatchError, whose getResults() holds every recipient: `failed`, or `unconfirmed` when an attempt may have - * queued it. The code `content_too_large` (413) means the batch is larger than PostHog takes: split the - * recipients into smaller batches. `batch_unavailable` (409) means the project can't send batches yet, and is - * never retried. + * queued it. getFix() carries PostHog's advice. The code `content_too_large` with status 413 means the request + * is larger than PostHog takes: send fewer recipients in each batch, or a smaller email. With status 400 it means + * the shared content is too large, so fewer recipients won't help: make the content or template_data smaller. + * `batch_unavailable` (409) means the project can't send batches yet, and is never retried. * `not_found` (404) means the template doesn't exist or batch sends are off for the project. For both, send each * email the batch didn't queue with send() and its recipient's `idempotency_key`. * diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index 824abee..fefdfa3 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -31,10 +31,9 @@ final class EmailBatch private bool $mayHaveQueued = false; /** - * @param list $members - * @param string $opening The request body up to its first recipient. + * @param list $members */ - private function __construct(private array $members, private string $opening) + private function __construct(private array $members, private string $body) { } @@ -76,13 +75,19 @@ public static function prepare(array $shared, mixed $recipients): self } $members[] = $member; } - $pairs = []; - foreach ($shared as $name => $value) { - $pairs[] = self::encode((string) $name, 'The email') . ':' . self::encode($value, 'The email'); + $body = self::encode($shared, 'The email'); + $body[-1] = ','; + $body .= '"recipients":['; + foreach ($members as $index => $member) { + if ($index > 0) { + $body .= ','; + } + $body .= $member['wire']; + unset($members[$index]['wire'], $member); } - $opening = '{' . implode(',', [...$pairs, '"recipients":[']); + $body .= ']}'; - return new self($members, $opening); + return new self($members, $body); } /** @@ -178,14 +183,14 @@ private static function encode(mixed $payload, string $what, int $depth = 512): public function requestBody(): string { - return $this->opening . implode(',', array_column($this->members, 'wire')) . ']}'; + return $this->body; } public function lost(EmailError $error): EmailError { $this->mayHaveQueued = true; $inFlight = $error->getStatusCode() === 409 && $error->getErrorCode() === self::IN_FLIGHT; - $cause = $inFlight ? self::inFlight($error) : self::unconfirmed(null); + $cause = $inFlight ? self::sendAgain($error) : self::unconfirmed(null); $this->setAll('unconfirmed', $cause); return $error; @@ -230,6 +235,10 @@ private function settle(int $index, array $slot): void return; } $answer = self::slotError($error, $messageId); + if ($this->mayHaveQueued) { + $this->set($index, 'unconfirmed', $messageId, error: self::sendAgain($answer)); + return; + } $status = in_array($answer->getErrorCode(), self::UNCONFIRMED_CODES, true) ? 'unconfirmed' : 'failed'; $this->set($index, $status, $messageId, error: $answer); } @@ -303,7 +312,7 @@ private static function requestError(array $fields, int $status, array $headers) ]; } if ($status === 413) { - $answered['fix'] = 'Split the recipients into smaller batches.'; + $answered += ['fix' => 'Make the email or its template_data smaller, or send fewer recipients in each batch.']; } if (($answered['code'] ?? null) === 'batch_unavailable') { $answered['fix'] = 'Until batch sends are on for the project, ' . self::SEND_SINGLY; @@ -341,7 +350,7 @@ private static function unconfirmed(?string $messageId): EmailError ); } - private static function inFlight(EmailError $error): EmailError + private static function sendAgain(EmailError $error): EmailError { return new EmailError( $error->getErrorCode(), @@ -352,7 +361,8 @@ private static function inFlight(EmailError $error): EmailError $error->getDocsUrl(), $error->getField(), $error->getRetryAfterMs(), - $error + $error, + $error->getMessageId() ); } } diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index 1855999..c8a7af2 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -444,22 +444,47 @@ public function testMoreThan100RecipientsAreRefusedBeforeAnyRequest(): void $this->assertSame([], $this->requests); } - public function testABatchTooLargeForPostHogIsTheErrorAndSaysToSplitIt(): void + #[DataProvider('tooLargeAnswers')] + public function testABatchTooLargeForPostHogIsTheErrorWithPostHogsFix(int $status, array $answer, ?string $fix): void { - $this->reply(self::wholeCall(413, 'content_too_large')); + $this->reply([$status, json_encode($answer), []]); $error = $this->batchError(self::recipients(100), ['max_retries' => 2]); - $this->assertSame(['content_too_large', 413, 'Nope.'], [ + $this->assertSame(['content_too_large', $status, 'Nope.', $fix], [ $error->getErrorCode(), $error->getStatusCode(), $error->getMessage(), + $error->getFix(), ]); - $this->assertSame('Split the recipients into smaller batches.', $error->getFix()); $this->assertSame(self::times(100, 'failed'), self::statuses($error->getResults())); $this->assertCount(1, $this->requests); } + public static function tooLargeAnswers(): array + { + $answer = ['type' => 'invalid_request', 'code' => 'content_too_large', 'detail' => 'Nope.']; + + return [ + "a body too large, with PostHog's fix" => [ + 413, + [...$answer, 'fix' => 'Split the recipients into smaller batches.'], + 'Split the recipients into smaller batches.', + ], + 'a body too large, without a fix' => [ + 413, + $answer, + 'Make the email or its template_data smaller, or send fewer recipients in each batch.', + ], + 'shared content too large' => [ + 400, + [...$answer, 'fix' => 'Make the shared template_data smaller.'], + 'Make the shared template_data smaller.', + ], + 'shared content too large, without a fix' => [400, $answer, null], + ]; + } + public function testAHundredRecipientsGoOutInOneRequest(): void { $this->reply(self::allQueued()); @@ -478,7 +503,7 @@ public function testARecipientIsEncodedWithoutExtraCopiesOfItsData(): void $appMemory = str_repeat('b', 14 * 1024 * 1024); $emails = new PostHog\Emails('phs_secret', 'us.i.posthog.com', transport: static fn(): array => [ 200, - '{"results":[{"error":{"code":"content_too_large","detail":"Too large.","status":413}}]}', + '{"results":[{"message_id":"m0","error":{"code":"content_too_large","detail":"Too large.","status":400}}]}', [], ]); $result = $emails->batch([ @@ -491,6 +516,63 @@ public function testARecipientIsEncodedWithoutExtraCopiesOfItsData(): void $this->assertSame([0, 'failed content_too_large'], self::runWithMemoryLimit($script, '32M')); } + public function testAHundredRecipientsNearTheBodyLimitGoOutInTightMemory(): void + { + $script = <<<'PHP' + array_fill(0, 100, ['message_id' => 'm', 'status' => 'queued'])]); +$sent = 0; +$emails = new PostHog\Emails('phs_secret', 'us.i.posthog.com', transport: static function ( + string $method, + string $url, + array $headers, + string $body +) use ($slots, &$sent): array { + $sent = strlen($body); + return [200, $slots, []]; +}); +$recipients = []; +for ($index = 0; $index < 100; $index++) { + $recipients[] = ['to' => "user$index@example.com", 'template_data' => ['note' => str_repeat('x', 45000)]]; +} +$result = $emails->batch([ + 'recipients' => $recipients, + 'template_id' => '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b', +]); +$queued = array_filter($result->getResults(), static fn($r): bool => $r->getStatus() === 'queued'); +echo count($queued), ' ', $sent > 4500000 ? 'body sent' : "body of $sent bytes"; +PHP; + + $this->assertSame([0, '100 body sent'], self::runWithMemoryLimit($script, '35M')); + } + + public function testSharedDataTooLargeForPostHogComesBackAsItsRefusalInTightMemory(): void + { + $script = <<<'PHP' + [ + 413, + '{"type":"invalid_request","code":"content_too_large","detail":"Too large."}', + [], +]); +try { + $emails->batch([ + 'recipients' => [['to' => 'user@example.com']], + 'template_id' => '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b', + 'template_data' => ['note' => str_repeat('x', 7 * 1024 * 1024)], + ]); +} catch (PostHog\EmailBatchError $error) { + echo $error->getErrorCode(); +} +PHP; + + $this->assertSame([0, 'content_too_large'], self::runWithMemoryLimit($script, '32M')); + } + public function testARecipientNestedDeeperThanItsEncodingAllowsIsRefusedBeforeAnyRequest(): void { $nested = 'v'; @@ -567,11 +649,11 @@ public function testALongerClientTimeoutAppliesToABatchToo(): void $this->assertSame(['queued'], self::statuses($result->getResults())); } - public function testARetryAfterALostAnswerReportsWhatTheRetryAnswered(): void + public function testARecipientARetryRefusesAfterALostAnswerStaysUnconfirmedWithItsKey(): void { $this->reply( self::networkError(), - self::ok(self::queued('m0', true), self::refused('m1', 'idempotency_key_reused')) + self::ok(self::queued('m0', true), self::refused('m1', 'recipient_suppressed')) ); $recipients = self::recipients(2); unset($recipients[1]['idempotency_key']); @@ -585,8 +667,11 @@ public function testARetryAfterALostAnswerReportsWhatTheRetryAnswered(): void [$first, $second] = $result->getResults(); $this->assertSame($derived, $second->getIdempotencyKey()); $this->assertSame(['queued', 'm0', true], [$first->getStatus(), $first->getMessageId(), $first->isReplayed()]); - $this->assertSame(['failed', 'm1'], [$second->getStatus(), $second->getMessageId()]); - $this->assertSame('idempotency_key_reused', $second->getError()->getErrorCode()); + $this->assertSame(['unconfirmed', 'm1'], [$second->getStatus(), $second->getMessageId()]); + $this->assertSame( + ['recipient_suppressed', 'Send it again with the same idempotency_key within 24 hours, so it goes out once.'], + [$second->getError()->getErrorCode(), $second->getError()->getFix()] + ); } public function testAnAnswerTooLargeToReadLeavesTheRequestUnconfirmed(): void From ea0aaefad0ffe5034033f490c05902e4451a3b05 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:12:18 +0100 Subject: [PATCH 27/44] docs(emails): say a 400 content_too_large wants smaller or single sends Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- lib/Emails.php | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index cb3bd92..dffe394 100644 --- a/README.md +++ b/README.md @@ -109,7 +109,7 @@ foreach ($result->getResults() as $email) { - **Requests.** A batch takes 1 to 100 recipients and goes out in one request. The client waits at least 45 seconds for the answer. More than 100 recipients throws `invalid_recipients` before any request. - **Idempotency keys.** Every retry reuses each recipient's key, so a retry never queues an email twice. Without a key, the client makes one that covers its own retries but not a second call. When a batch may be cut off and run again, pass keys you store: send it again with the same key within 24 hours, so it goes out once. Each recipient of a call needs a different key. Build each key from an ID you store with the job, such as the digest's own ID, never from the time of the run: a retry after midnight would make new keys and send the emails again. Never reuse a key for another email: PostHog sends one email per key, so the other doesn't go out. PostHog usually refuses it with `idempotency_key_reused`, but two sends that arrive at the same time can both answer `queued`. - **Statuses.** `getStatus()` is `queued` when PostHog accepted the email, `failed` when it refused it (`getError()` says why, such as a suppressed address), and `unconfirmed` when the client can't tell, such as after a lost answer. Send each `unconfirmed` email again with the same key within 24 hours, so it goes out once. `getWarnings()` holds PostHog's warnings. -- **Errors.** When PostHog refuses the batch as a whole, such as a rate limit past its retries, `batch()` throws `PostHog\EmailBatchError`, whose `getResults()` holds every recipient. `getFix()` carries PostHog's advice. `content_too_large` with status 413 means the request is larger than PostHog takes: send fewer recipients in each batch, or a smaller email. With status 400 it means the shared content is too large, so fewer recipients won't help: make the content or `template_data` smaller. `batch_unavailable` (409) means the project can't send batches yet, and is never retried. `not_found` (404) means the template doesn't exist or batch sends are off. For both, send each email the batch didn't queue with `send()` and its recipient's `idempotency_key`. +- **Errors.** When PostHog refuses the batch as a whole, such as a rate limit past its retries, `batch()` throws `PostHog\EmailBatchError`, whose `getResults()` holds every recipient. `getFix()` carries PostHog's advice. `content_too_large` with status 413 means the request is larger than PostHog takes: send fewer recipients in each batch, or a smaller email. With status 400 it means the content or `template_data` every recipient shares is too large, so fewer recipients won't help: make it smaller, or send those emails one at a time with `send()`. `batch_unavailable` (409) means the project can't send batches yet, and is never retried. `not_found` (404) means the template doesn't exist or batch sends are off. For both, send each email the batch didn't queue with `send()` and its recipient's `idempotency_key`. ## Questions? diff --git a/lib/Emails.php b/lib/Emails.php index 2201906..b2d41f9 100644 --- a/lib/Emails.php +++ b/lib/Emails.php @@ -438,7 +438,8 @@ public function get(string $messageId): EmailStatus * EmailBatchError, whose getResults() holds every recipient: `failed`, or `unconfirmed` when an attempt may have * queued it. getFix() carries PostHog's advice. The code `content_too_large` with status 413 means the request * is larger than PostHog takes: send fewer recipients in each batch, or a smaller email. With status 400 it means - * the shared content is too large, so fewer recipients won't help: make the content or template_data smaller. + * the content or template_data every recipient shares is too large, so fewer recipients won't help: make it + * smaller, or send those emails one at a time with send(). * `batch_unavailable` (409) means the project can't send batches yet, and is never retried. * `not_found` (404) means the template doesn't exist or batch sends are off for the project. For both, send each * email the batch didn't queue with send() and its recipient's `idempotency_key`. From efdab6e02fc94fc75039c7edf716130dcbb3895e Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:21:55 +0100 Subject: [PATCH 28/44] fix(emails): encode each batch recipient into the body, advise resends - Each recipient is encoded straight into the request body instead of being held encoded until the body is built, so a batch near PostHog's body limit fits a tighter PHP memory limit. - Every unconfirmed recipient carries the same-key resend advice, also when PostHog's first answer leaves it unconfirmed or unreadable. Co-Authored-By: Claude Opus 5.5 --- lib/Internal/EmailBatch.php | 24 +++++++----------- test/EmailsBatchTest.php | 49 +++++++++++++++++++++++++++---------- 2 files changed, 45 insertions(+), 28 deletions(-) diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index fefdfa3..de9f24b 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -82,7 +82,7 @@ public static function prepare(array $shared, mixed $recipients): self if ($index > 0) { $body .= ','; } - $body .= $member['wire']; + $body .= self::joined($index, $member['wire']); unset($members[$index]['wire'], $member); } $body .= ']}'; @@ -91,7 +91,7 @@ public static function prepare(array $shared, mixed $recipients): self } /** - * @return array{to: string, key: string, wire: string} + * @return array{to: string, key: string, wire: array} */ private static function member(int $index, mixed $recipient, bool $isTemplateForm): array { @@ -123,22 +123,17 @@ private static function member(int $index, mixed $recipient, bool $isTemplateFor if (array_key_exists('template_data', $recipient)) { $wire['message_data'] = self::templateData($index, $recipient['template_data'], $isTemplateForm); } - $values = []; - foreach ($wire as $name => $value) { - $values[$name] = self::encode($value, "recipients[$index]", 511); - } - - return ['to' => $to, 'key' => $wire['idempotency_key'], 'wire' => self::joined($values)]; + return ['to' => $to, 'key' => $wire['idempotency_key'], 'wire' => $wire]; } /** - * @param array $values + * @param array $wire */ - private static function joined(array $values): string + private static function joined(int $index, array $wire): string { $parts = []; - foreach ($values as $name => $json) { - array_push($parts, $parts === [] ? '{' : ',', "\"$name\":", $json); + foreach ($wire as $name => $value) { + array_push($parts, $parts === [] ? '{' : ',', "\"$name\":", self::encode($value, "recipients[$index]", 511)); } $parts[] = '}'; @@ -235,12 +230,11 @@ private function settle(int $index, array $slot): void return; } $answer = self::slotError($error, $messageId); - if ($this->mayHaveQueued) { + if ($this->mayHaveQueued || in_array($answer->getErrorCode(), self::UNCONFIRMED_CODES, true)) { $this->set($index, 'unconfirmed', $messageId, error: self::sendAgain($answer)); return; } - $status = in_array($answer->getErrorCode(), self::UNCONFIRMED_CODES, true) ? 'unconfirmed' : 'failed'; - $this->set($index, $status, $messageId, error: $answer); + $this->set($index, 'failed', $messageId, error: $answer); } public function result(): SendBatchResult diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index c8a7af2..35be33e 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -521,17 +521,24 @@ public function testAHundredRecipientsNearTheBodyLimitGoOutInTightMemory(): void $script = <<<'PHP' array_fill(0, 100, ['message_id' => 'm', 'status' => 'queued'])]); +$appMemory = str_repeat('b', 16 * 1024 * 1024); $sent = 0; $emails = new PostHog\Emails('phs_secret', 'us.i.posthog.com', transport: static function ( string $method, string $url, array $headers, string $body -) use ($slots, &$sent): array { +) use (&$sent): array { + preg_match_all('/"idempotency_key":"([^"]+)"/', $body, $keys); + $valid = PHP_VERSION_ID < 80300 || json_validate($body); + if (!$valid || !str_ends_with($body, ']}') || count(array_unique($keys[1])) !== 100) { + return [400, '{"type":"invalid_request","code":"invalid_request","detail":"Not a batch."}', []]; + } $sent = strlen($body); - return [200, $slots, []]; + return [200, json_encode(['results' => array_map( + static fn(string $key): array => ['message_id' => "msg-$key", 'status' => 'queued'], + $keys[1] + )]), []]; }); $recipients = []; for ($index = 0; $index < 100; $index++) { @@ -541,11 +548,11 @@ public function testAHundredRecipientsNearTheBodyLimitGoOutInTightMemory(): void 'recipients' => $recipients, 'template_id' => '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b', ]); -$queued = array_filter($result->getResults(), static fn($r): bool => $r->getStatus() === 'queued'); -echo count($queued), ' ', $sent > 4500000 ? 'body sent' : "body of $sent bytes"; +$ids = array_map(static fn($r): ?string => $r->getStatus() === 'queued' ? $r->getMessageId() : null, $result->getResults()); +echo count(array_unique(array_filter($ids))), ' ', $sent > 4500000 ? 'body sent' : "body of $sent bytes"; PHP; - $this->assertSame([0, '100 body sent'], self::runWithMemoryLimit($script, '35M')); + $this->assertSame([0, '100 body sent'], self::runWithMemoryLimit($script, '32M')); } public function testSharedDataTooLargeForPostHogComesBackAsItsRefusalInTightMemory(): void @@ -699,18 +706,34 @@ public function testA503ThenARefusalOfTheWholeRequestKeepsTheRecipientUnconfirme $this->assertSame('delivery_unavailable', $result->getError()->getErrorCode()); } - public function testARecipientThePipelineDidNotConfirmIsUnconfirmed(): void - { - $this->reply(self::ok(self::notConfirmed())); + #[DataProvider('slotsWithoutAConfirmation')] + public function testARecipientPostHogDidNotConfirmIsUnconfirmedWithTheAdviceToSendAgain( + array $slot, + array $error + ): void { + $this->reply(self::ok($slot)); [$result] = $this->batch(self::recipients(1))->getResults(); - $this->assertSame(['unconfirmed', 'm0'], [$result->getStatus(), $result->getMessageId()]); - $this->assertSame(['delivery_unavailable', 503], [ + $this->assertSame(['unconfirmed', 'm0', 'key-0'], [ + $result->getStatus(), + $result->getMessageId(), + $result->getIdempotencyKey(), + ]); + $sendAgain = 'Send it again with the same idempotency_key within 24 hours, so it goes out once.'; + $this->assertSame([...$error, $sendAgain], [ $result->getError()->getErrorCode(), $result->getError()->getStatusCode(), + $result->getError()->getFix(), ]); - $this->assertSame('key-0', $result->getIdempotencyKey()); + } + + public static function slotsWithoutAConfirmation(): array + { + return [ + 'not confirmed by the pipeline' => [self::notConfirmed(), ['delivery_unavailable', 503]], + 'an unreadable result' => [['message_id' => 'm0', 'status' => 'pending'], ['api_error', null]], + ]; } public function testABatchThatSucceedsReadsNothingBackForAnUnconfirmedEmail(): void From 0ea8d1694e0531d3f3517d947141b41f5ce387be Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:36:30 +0100 Subject: [PATCH 29/44] fix(emails): encode a batch request once, keep refusals on recipients - The request is encoded in one json_encode call, so a batch holds only the caller's input and the body. Encoding errors are traced to the shared fields or a recipient only when that call fails. - A whole-request refusal after an attempt that may have queued leaves each recipient unconfirmed with the refusal and the resend advice. - An empty fix from PostHog on a 413 falls back to the SDK's advice. Co-Authored-By: Claude Opus 5.5 --- lib/Internal/EmailBatch.php | 52 +++++++++++++++--------------------- test/EmailsBatchTest.php | 53 ++++++++++++++++++++++++++++--------- 2 files changed, 62 insertions(+), 43 deletions(-) diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index de9f24b..f88773c 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -60,6 +60,7 @@ public static function prepare(array $shared, mixed $recipients): self } $isTemplateForm = array_key_exists('template_id', $shared); $members = []; + $wires = []; $firstWithKey = []; foreach ($recipients as $index => $recipient) { $member = self::member($index, $recipient, $isTemplateForm); @@ -73,21 +74,20 @@ public static function prepare(array $shared, mixed $recipients): self field: "recipients__{$index}__idempotency_key" ); } - $members[] = $member; + $members[] = ['to' => $member['to'], 'key' => $member['key']]; + $wires[] = $member['wire']; } - $body = self::encode($shared, 'The email'); - $body[-1] = ','; - $body .= '"recipients":['; - foreach ($members as $index => $member) { - if ($index > 0) { - $body .= ','; + $request = [...$shared, 'recipients' => $wires]; + try { + return new self($members, json_encode($request, self::JSON_FLAGS)); + } catch (JsonException) { + self::encode($shared, 'The email'); + foreach ($wires as $index => $wire) { + self::encode($wire, "recipients[$index]", 510); } - $body .= self::joined($index, $member['wire']); - unset($members[$index]['wire'], $member); - } - $body .= ']}'; - return new self($members, $body); + return new self($members, self::encode($request, 'The email')); + } } /** @@ -126,20 +126,6 @@ private static function member(int $index, mixed $recipient, bool $isTemplateFor return ['to' => $to, 'key' => $wire['idempotency_key'], 'wire' => $wire]; } - /** - * @param array $wire - */ - private static function joined(int $index, array $wire): string - { - $parts = []; - foreach ($wire as $name => $value) { - array_push($parts, $parts === [] ? '{' : ',', "\"$name\":", self::encode($value, "recipients[$index]", 511)); - } - $parts[] = '}'; - - return implode('', $parts); - } - private static function templateData(int $index, mixed $data, bool $isTemplateForm): array|object { $field = "recipients__{$index}__template_data"; @@ -185,7 +171,7 @@ public function lost(EmailError $error): EmailError { $this->mayHaveQueued = true; $inFlight = $error->getStatusCode() === 409 && $error->getErrorCode() === self::IN_FLIGHT; - $cause = $inFlight ? self::sendAgain($error) : self::unconfirmed(null); + $cause = $inFlight ? self::sendAgain($error, $error->getFix() ?? self::SEND_AGAIN) : self::unconfirmed(null); $this->setAll('unconfirmed', $cause); return $error; @@ -202,6 +188,9 @@ public function answer(int $status, string $body, array $headers): void if ($status >= 500 || ($status === 409 && $error->getErrorCode() === self::IN_FLIGHT)) { throw $this->lost($error); } + if ($this->mayHaveQueued) { + $this->setAll('unconfirmed', self::sendAgain($error, self::SEND_AGAIN)); + } throw $error; } $slots = $fields['results'] ?? null; @@ -231,7 +220,7 @@ private function settle(int $index, array $slot): void } $answer = self::slotError($error, $messageId); if ($this->mayHaveQueued || in_array($answer->getErrorCode(), self::UNCONFIRMED_CODES, true)) { - $this->set($index, 'unconfirmed', $messageId, error: self::sendAgain($answer)); + $this->set($index, 'unconfirmed', $messageId, error: self::sendAgain($answer, self::SEND_AGAIN)); return; } $this->set($index, 'failed', $messageId, error: $answer); @@ -306,7 +295,8 @@ private static function requestError(array $fields, int $status, array $headers) ]; } if ($status === 413) { - $answered += ['fix' => 'Make the email or its template_data smaller, or send fewer recipients in each batch.']; + $answered['fix'] = EmailReplies::text($answered['fix'] ?? null) + ?? 'Make the email or its template_data smaller, or send fewer recipients in each batch.'; } if (($answered['code'] ?? null) === 'batch_unavailable') { $answered['fix'] = 'Until batch sends are on for the project, ' . self::SEND_SINGLY; @@ -344,14 +334,14 @@ private static function unconfirmed(?string $messageId): EmailError ); } - private static function sendAgain(EmailError $error): EmailError + private static function sendAgain(EmailError $error, string $fix): EmailError { return new EmailError( $error->getErrorCode(), $error->getMessage(), $error->getStatusCode(), $error->getWhy(), - $error->getFix() ?? self::SEND_AGAIN, + $fix, $error->getDocsUrl(), $error->getField(), $error->getRetryAfterMs(), diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index 35be33e..fe566a7 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -482,6 +482,11 @@ public static function tooLargeAnswers(): array 'Make the shared template_data smaller.', ], 'shared content too large, without a fix' => [400, $answer, null], + 'a body too large, with an empty fix' => [ + 413, + [...$answer, 'fix' => ''], + 'Make the email or its template_data smaller, or send fewer recipients in each batch.', + ], ]; } @@ -516,9 +521,11 @@ public function testARecipientIsEncodedWithoutExtraCopiesOfItsData(): void $this->assertSame([0, 'failed content_too_large'], self::runWithMemoryLimit($script, '32M')); } - public function testAHundredRecipientsNearTheBodyLimitGoOutInTightMemory(): void + #[DataProvider('recipientsNearTheBodyLimit')] + public function testAHundredRecipientsNearTheBodyLimitGoOutInTightMemory(int $each, int $last): void { - $script = <<<'PHP' + $bodyFile = tempnam(sys_get_temp_dir(), 'posthog-emails-batch-body-'); + $script = "" . <<<'PHP' array_map( static fn(string $key): array => ['message_id' => "msg-$key", 'status' => 'queued'], @@ -542,7 +546,8 @@ public function testAHundredRecipientsNearTheBodyLimitGoOutInTightMemory(): void }); $recipients = []; for ($index = 0; $index < 100; $index++) { - $recipients[] = ['to' => "user$index@example.com", 'template_data' => ['note' => str_repeat('x', 45000)]]; + $size = $index === 99 ? $last : $each; + $recipients[] = ['to' => "user$index@example.com", 'template_data' => ['note' => str_repeat('x', $size)]]; } $result = $emails->batch([ 'recipients' => $recipients, @@ -552,7 +557,25 @@ public function testAHundredRecipientsNearTheBodyLimitGoOutInTightMemory(): void echo count(array_unique(array_filter($ids))), ' ', $sent > 4500000 ? 'body sent' : "body of $sent bytes"; PHP; - $this->assertSame([0, '100 body sent'], self::runWithMemoryLimit($script, '32M')); + try { + $this->assertSame([0, '100 body sent'], self::runWithMemoryLimit($script, '32M')); + $request = json_decode(file_get_contents($bodyFile), true, flags: JSON_THROW_ON_ERROR); + } finally { + unlink($bodyFile); + } + $this->assertSame([...array_fill(0, 99, $each), $last], array_map( + static fn(array $recipient): int => strlen($recipient['message_data']['note']), + $request['recipients'] + )); + $this->assertCount(100, array_unique(array_column($request['recipients'], 'idempotency_key'))); + } + + public static function recipientsNearTheBodyLimit(): array + { + return [ + 'evenly sized' => [45000, 45000], + 'one large recipient' => [2020, 4800000], + ]; } public function testSharedDataTooLargeForPostHogComesBackAsItsRefusalInTightMemory(): void @@ -703,7 +726,10 @@ public function testA503ThenARefusalOfTheWholeRequestKeepsTheRecipientUnconfirme $this->assertSame(['sending_paused', 422], [$error->getErrorCode(), $error->getStatusCode()]); [$result] = $error->getResults(); $this->assertSame('unconfirmed', $result->getStatus()); - $this->assertSame('delivery_unavailable', $result->getError()->getErrorCode()); + $this->assertSame( + ['sending_paused', 422, 'Send it again with the same idempotency_key within 24 hours, so it goes out once.'], + [$result->getError()->getErrorCode(), $result->getError()->getStatusCode(), $result->getError()->getFix()] + ); } #[DataProvider('slotsWithoutAConfirmation')] @@ -860,7 +886,7 @@ public function testARequestRefusedAsAWholeThrowsWithEveryRecipient(): void $this->assertSame('key-2', $results[2]->getIdempotencyKey()); } - public function testARefusalOfTheWholeRequestAfterALostAnswerKeepsItsRecipientsUnconfirmed(): void + public function testARefusalOfTheWholeRequestAfterALostAnswerKeepsItsRecipientsUnconfirmedWithTheRefusal(): void { $this->reply(self::networkError(), self::wholeCall(429, 'quota_limited')); @@ -868,7 +894,10 @@ public function testARefusalOfTheWholeRequestAfterALostAnswerKeepsItsRecipientsU [$result] = $error->getResults(); $this->assertSame(['unconfirmed', null], [$result->getStatus(), $result->getMessageId()]); - $this->assertSame('delivery_unavailable', $result->getError()->getErrorCode()); + $this->assertSame( + ['quota_limited', 429, 'Send it again with the same idempotency_key within 24 hours, so it goes out once.'], + [$result->getError()->getErrorCode(), $result->getError()->getStatusCode(), $result->getError()->getFix()] + ); $this->assertSame([self::BATCH_URL, self::BATCH_URL], $this->requestUrls()); } From c17dafd6ec327a495f03a7306c135f8132038575 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:44:35 +0100 Subject: [PATCH 30/44] fix(emails): never send a batch after a failed encode, dedupe warnings - When encoding the batch fails, the client traces the failing field and then throws, instead of encoding again: a value that encodes only on a later call no longer goes out. - A warning PostHog repeats in one answer reaches the caller once. Co-Authored-By: Claude Opus 5.5 --- lib/Internal/EmailBatch.php | 26 +++++++++++++++++--------- test/EmailsBatchTest.php | 23 ++++++++++++++++++++++- 2 files changed, 39 insertions(+), 10 deletions(-) diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index f88773c..50210dd 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -80,13 +80,12 @@ public static function prepare(array $shared, mixed $recipients): self $request = [...$shared, 'recipients' => $wires]; try { return new self($members, json_encode($request, self::JSON_FLAGS)); - } catch (JsonException) { + } catch (JsonException $exception) { self::encode($shared, 'The email'); foreach ($wires as $index => $wire) { self::encode($wire, "recipients[$index]", 510); } - - return new self($members, self::encode($request, 'The email')); + throw self::unencodable('The email', $exception); } } @@ -154,14 +153,19 @@ private static function encode(mixed $payload, string $what, int $depth = 512): try { return json_encode($payload, self::JSON_FLAGS, $depth); } catch (JsonException $exception) { - throw new EmailError( - 'invalid_form', - "$what could not be encoded as JSON, so no email was sent: " . $exception->getMessage() . '.', - previous: $exception - ); + throw self::unencodable($what, $exception); } } + private static function unencodable(string $what, JsonException $exception): EmailError + { + return new EmailError( + 'invalid_form', + "$what could not be encoded as JSON, so no email was sent: " . $exception->getMessage() . '.', + previous: $exception + ); + } + public function requestBody(): string { return $this->body; @@ -204,7 +208,11 @@ public function answer(int $status, string $body, array $headers): void foreach (array_keys($this->members) as $index) { $this->settle($index, is_array($slots[$index]) ? $slots[$index] : []); } - $this->warnings = EmailReplies::warnings($fields); + foreach (EmailReplies::warnings($fields) as $warning) { + if (!in_array($warning, $this->warnings)) { + $this->warnings[] = $warning; + } + } } /** diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index fe566a7..a24446b 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -5,6 +5,7 @@ use Closure; use DateTimeImmutable; use DateTimeZone; +use JsonSerializable; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use PostHog\BatchEmailResult; @@ -603,6 +604,26 @@ public function testSharedDataTooLargeForPostHogComesBackAsItsRefusalInTightMemo $this->assertSame([0, 'content_too_large'], self::runWithMemoryLimit($script, '32M')); } + public function testAValueThatFailsToEncodeOnceSendsNothingEvenIfItWouldEncodeLater(): void + { + $value = new class implements JsonSerializable { + private int $calls = 0; + + public function jsonSerialize(): mixed + { + return ++$this->calls === 1 ? NAN : 'later'; + } + }; + + try { + $this->batch(self::recipients(1, ['template_data' => ['note' => $value]])); + $this->fail('Expected invalid_form'); + } catch (EmailError $error) { + $this->assertSame('invalid_form', $error->getErrorCode()); + } + $this->assertSame([], $this->requests); + } + public function testARecipientNestedDeeperThanItsEncodingAllowsIsRefusedBeforeAnyRequest(): void { $nested = 'v'; @@ -1024,7 +1045,7 @@ public function testWarningsReachTheCallerOnce(): void { global $errorMessages; $warning = ['code' => 'sandbox_sender', 'detail' => 'Sent from the test sender.']; - $this->reply(self::allQueued(['warnings' => [$warning]])); + $this->reply(self::allQueued(['warnings' => [$warning, $warning]])); $result = $this->batch(self::recipients(2)); From d28b91b345eac3d934b07e13aa0f17998b0608c8 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:53:05 +0100 Subject: [PATCH 31/44] fix(emails): refuse an unencodable batch even if a later encode throws - Tracing which field failed to encode can't let a serializer's later exception replace the invalid_form error; nothing is sent either way. - Test lines wrapped to the 120-character limit CI checks. Co-Authored-By: Claude Opus 5.5 --- lib/Internal/EmailBatch.php | 12 +++++++--- test/EmailsBatchTest.php | 45 ++++++++++++++++++++++++++++++------- 2 files changed, 46 insertions(+), 11 deletions(-) diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index 50210dd..3fa8033 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -9,6 +9,7 @@ use PostHog\EmailWarning; use PostHog\SendBatchResult; use PostHog\Uuid; +use Throwable; /** * @internal @@ -81,9 +82,14 @@ public static function prepare(array $shared, mixed $recipients): self try { return new self($members, json_encode($request, self::JSON_FLAGS)); } catch (JsonException $exception) { - self::encode($shared, 'The email'); - foreach ($wires as $index => $wire) { - self::encode($wire, "recipients[$index]", 510); + try { + self::encode($shared, 'The email'); + foreach ($wires as $index => $wire) { + self::encode($wire, "recipients[$index]", 510); + } + } catch (EmailError $traced) { + throw $traced; + } catch (Throwable) { } throw self::unencodable('The email', $exception); } diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index a24446b..8b9a0a7 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -13,6 +13,7 @@ use PostHog\EmailError; use PostHog\Emails; use PostHog\SendBatchResult; +use RuntimeException; use stdClass; use Symfony\Component\Clock\Clock; use Symfony\Component\Clock\ClockInterface; @@ -446,8 +447,11 @@ public function testMoreThan100RecipientsAreRefusedBeforeAnyRequest(): void } #[DataProvider('tooLargeAnswers')] - public function testABatchTooLargeForPostHogIsTheErrorWithPostHogsFix(int $status, array $answer, ?string $fix): void - { + public function testABatchTooLargeForPostHogIsTheErrorWithPostHogsFix( + int $status, + array $answer, + ?string $fix + ): void { $this->reply([$status, json_encode($answer), []]); $error = $this->batchError(self::recipients(100), ['max_retries' => 2]); @@ -554,7 +558,10 @@ public function testAHundredRecipientsNearTheBodyLimitGoOutInTightMemory(int $ea 'recipients' => $recipients, 'template_id' => '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b', ]); -$ids = array_map(static fn($r): ?string => $r->getStatus() === 'queued' ? $r->getMessageId() : null, $result->getResults()); +$ids = array_map( + static fn($r): ?string => $r->getStatus() === 'queued' ? $r->getMessageId() : null, + $result->getResults() +); echo count(array_unique(array_filter($ids))), ' ', $sent > 4500000 ? 'body sent' : "body of $sent bytes"; PHP; @@ -604,14 +611,19 @@ public function testSharedDataTooLargeForPostHogComesBackAsItsRefusalInTightMemo $this->assertSame([0, 'content_too_large'], self::runWithMemoryLimit($script, '32M')); } - public function testAValueThatFailsToEncodeOnceSendsNothingEvenIfItWouldEncodeLater(): void + #[DataProvider('laterSerializations')] + public function testAValueThatFailsToEncodeOnceIsRefusedWithoutARequestWhateverItDoesLater(Closure $later): void { - $value = new class implements JsonSerializable { + $value = new class ($later) implements JsonSerializable { private int $calls = 0; + public function __construct(private Closure $later) + { + } + public function jsonSerialize(): mixed { - return ++$this->calls === 1 ? NAN : 'later'; + return ++$this->calls === 1 ? NAN : ($this->later)(); } }; @@ -624,6 +636,16 @@ public function jsonSerialize(): mixed $this->assertSame([], $this->requests); } + public static function laterSerializations(): array + { + return [ + 'encodes later' => [static fn(): string => 'later'], + 'throws later' => [static function (): never { + throw new RuntimeException('Serialized once already.'); + }], + ]; + } + public function testARecipientNestedDeeperThanItsEncodingAllowsIsRefusedBeforeAnyRequest(): void { $nested = 'v'; @@ -720,7 +742,10 @@ public function testARecipientARetryRefusesAfterALostAnswerStaysUnconfirmedWithI $this->assertSame(['queued', 'm0', true], [$first->getStatus(), $first->getMessageId(), $first->isReplayed()]); $this->assertSame(['unconfirmed', 'm1'], [$second->getStatus(), $second->getMessageId()]); $this->assertSame( - ['recipient_suppressed', 'Send it again with the same idempotency_key within 24 hours, so it goes out once.'], + [ + 'recipient_suppressed', + 'Send it again with the same idempotency_key within 24 hours, so it goes out once.', + ], [$second->getError()->getErrorCode(), $second->getError()->getFix()] ); } @@ -748,7 +773,11 @@ public function testA503ThenARefusalOfTheWholeRequestKeepsTheRecipientUnconfirme [$result] = $error->getResults(); $this->assertSame('unconfirmed', $result->getStatus()); $this->assertSame( - ['sending_paused', 422, 'Send it again with the same idempotency_key within 24 hours, so it goes out once.'], + [ + 'sending_paused', + 422, + 'Send it again with the same idempotency_key within 24 hours, so it goes out once.', + ], [$result->getError()->getErrorCode(), $result->getError()->getStatusCode(), $result->getError()->getFix()] ); } From 79513562cdbd2b59837c4e06f4a8315afe227aa5 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:08:34 +0100 Subject: [PATCH 32/44] fix(emails): report a batch that fails to encode without encoding it again A batch whose data fails to encode now fails with invalid_form at once, without running the caller's serializers a second time. The oversized answer is tested against the loopback server, and the near-limit memory test only uses recipients PostHog can queue. Co-Authored-By: Claude Opus 5.5 --- lib/Internal/EmailBatch.php | 33 +++++---------------------------- test/EmailsBatchTest.php | 23 ++++++----------------- test/EmailsClientTest.php | 21 +++++++++++++++++++++ 3 files changed, 32 insertions(+), 45 deletions(-) diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index 3fa8033..b756837 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -9,7 +9,6 @@ use PostHog\EmailWarning; use PostHog\SendBatchResult; use PostHog\Uuid; -use Throwable; /** * @internal @@ -82,16 +81,11 @@ public static function prepare(array $shared, mixed $recipients): self try { return new self($members, json_encode($request, self::JSON_FLAGS)); } catch (JsonException $exception) { - try { - self::encode($shared, 'The email'); - foreach ($wires as $index => $wire) { - self::encode($wire, "recipients[$index]", 510); - } - } catch (EmailError $traced) { - throw $traced; - } catch (Throwable) { - } - throw self::unencodable('The email', $exception); + throw new EmailError( + 'invalid_form', + 'The email could not be encoded as JSON, so no email was sent: ' . $exception->getMessage() . '.', + previous: $exception + ); } } @@ -154,23 +148,6 @@ private static function templateData(int $index, mixed $data, bool $isTemplateFo return $data === [] ? (object) [] : $data; } - private static function encode(mixed $payload, string $what, int $depth = 512): string - { - try { - return json_encode($payload, self::JSON_FLAGS, $depth); - } catch (JsonException $exception) { - throw self::unencodable($what, $exception); - } - } - - private static function unencodable(string $what, JsonException $exception): EmailError - { - return new EmailError( - 'invalid_form', - "$what could not be encoded as JSON, so no email was sent: " . $exception->getMessage() . '.', - previous: $exception - ); - } public function requestBody(): string { diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index 8b9a0a7..e96d37b 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -541,12 +541,11 @@ public function testAHundredRecipientsNearTheBodyLimitGoOutInTightMemory(int $ea array $headers, string $body ) use (&$sent, $bodyFile): array { - preg_match_all('/"idempotency_key":"([^"]+)"/', $body, $keys); file_put_contents($bodyFile, $body); $sent = strlen($body); return [200, json_encode(['results' => array_map( - static fn(string $key): array => ['message_id' => "msg-$key", 'status' => 'queued'], - $keys[1] + static fn(int $index): array => ['message_id' => "msg-$index", 'status' => 'queued'], + range(0, 99) )]), []]; }); $recipients = []; @@ -582,7 +581,7 @@ public static function recipientsNearTheBodyLimit(): array { return [ 'evenly sized' => [45000, 45000], - 'one large recipient' => [2020, 4800000], + 'one recipient near the per-email limit' => [32000, 1400000], ]; } @@ -643,6 +642,9 @@ public static function laterSerializations(): array 'throws later' => [static function (): never { throw new RuntimeException('Serialized once already.'); }], + 'throws an email error later' => [static function (): never { + throw new EmailError('network_error', 'Not a network error.'); + }], ]; } @@ -750,19 +752,6 @@ public function testARecipientARetryRefusesAfterALostAnswerStaysUnconfirmedWithI ); } - public function testAnAnswerTooLargeToReadLeavesTheRequestUnconfirmed(): void - { - $this->reply( - new EmailError('response_too_large', 'PostHog answered with more than 1048576 bytes.') - ); - - $error = $this->batchError(self::recipients(1)); - - $this->assertSame('response_too_large', $error->getErrorCode()); - $this->assertSame(['unconfirmed'], self::statuses($error->getResults())); - $this->assertSame([self::BATCH_URL], $this->requestUrls()); - } - public function testA503ThenARefusalOfTheWholeRequestKeepsTheRecipientUnconfirmed(): void { $this->reply(self::wholeCall(503, 'delivery_unavailable'), self::wholeCall(422, 'sending_paused')); diff --git a/test/EmailsClientTest.php b/test/EmailsClientTest.php index 079b96b..93654d5 100644 --- a/test/EmailsClientTest.php +++ b/test/EmailsClientTest.php @@ -5,6 +5,7 @@ use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use PostHog\Client; +use PostHog\EmailBatchError; use PostHog\EmailError; use PostHog\PostHog; @@ -334,6 +335,26 @@ public function testAnOversizedReplyIsNotReadOrRetried(): void $this->assertCount(2, $this->server->requests()); } + public function testABatchWhoseAnswerIsTooLargeToReadLeavesItsRecipientsUnconfirmedWithTheirKeys(): void + { + $this->server = new LocalHttpServer([ + ['status' => 200, 'body' => '{"results":[]}', 'pad_body_bytes' => 2_000_000], + ]); + + try { + $this->client()->emails()->batch([ + 'recipients' => [['to' => 'user@example.com', 'idempotency_key' => 'welcome:user']], + 'template_id' => self::TEMPLATE_ID, + ]); + $this->fail('batch() did not throw'); + } catch (EmailBatchError $error) { + $this->assertSame('response_too_large', $error->getErrorCode()); + [$result] = $error->getResults(); + $this->assertSame(['unconfirmed', 'welcome:user'], [$result->getStatus(), $result->getIdempotencyKey()]); + } + $this->assertCount(1, $this->server->requests()); + } + public function testAClosedPortIsANetworkError(): void { $this->server = new LocalHttpServer(); From b5bf73a2f292248cc3ff98effb53344b9d834d46 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:08:57 +0100 Subject: [PATCH 33/44] docs(emails): say an unconfirmed batch result can carry any code Co-Authored-By: Claude Opus 5.5 --- lib/BatchEmailResult.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/BatchEmailResult.php b/lib/BatchEmailResult.php index 3fcd0b6..5229ff0 100644 --- a/lib/BatchEmailResult.php +++ b/lib/BatchEmailResult.php @@ -81,8 +81,9 @@ public function isReplayed(): bool } /** - * Why the email is not `queued`, or null when it is. For an `unconfirmed` email, the code is - * `delivery_unavailable`, `idempotency_key_in_flight` or `api_error`. + * Why the email is not `queued`, or null when it is. An `unconfirmed` email can carry any code, such as + * `delivery_unavailable`, `idempotency_key_in_flight`, or the refusal of a retry after a lost answer, so decide + * whether to send it again from getStatus(), not from the code. */ public function getError(): ?EmailError { From 7cf8fb272ae3b75e3507416c98b582b27f78ad39 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:21:12 +0100 Subject: [PATCH 34/44] test(emails): cover a shutdown after a lost batch answer and an in-flight fix Co-Authored-By: Claude Opus 5.5 --- test/EmailsBatchTest.php | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index e96d37b..0e6eb01 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -840,6 +840,23 @@ public function testAWholeRequestInFlightAnswerLeavesItsRecipientsUnconfirmed(): $this->assertSame([self::BATCH_URL], $this->requestUrls()); } + public function testAWholeRequestInFlightAnswerKeepsPostHogsFixOnItsRecipients(): void + { + $this->reply([409, json_encode([ + 'type' => 'invalid_request', + 'code' => 'idempotency_key_in_flight', + 'detail' => 'Nope.', + 'fix' => 'Wait a minute, then send it again with the same idempotency_key.', + ]), []]); + + $error = $this->batchError(self::recipients(1), ['max_retries' => 0]); + + $this->assertSame( + 'Wait a minute, then send it again with the same idempotency_key.', + $error->getResults()[0]->getError()->getFix() + ); + } + public static function attemptsAfterAnInFlightAnswer(): array { return [ @@ -883,6 +900,27 @@ public function testAShutdownDuringARetryWaitSendsNoRetry(): void $this->assertSame('client_closed', $error->getResults()[0]->getError()->getErrorCode()); } + public function testAShutdownWhileWaitingToRetryALostAnswerKeepsItsRecipientsUnconfirmedWithTheirKeys(): void + { + Clock::set(self::clockThatShutsDownOnSleep($this->clock, function (): void { + $this->closed = true; + })); + $this->reply(self::networkError(), self::allQueued()); + + $error = $this->batchError( + [['to' => 'a@example.com'], ['to' => 'b@example.com']], + emails: $this->closedEmails() + ); + + $this->assertSame('client_closed', $error->getErrorCode()); + $this->assertCount(1, $this->requests); + $this->assertSame(['unconfirmed', 'unconfirmed'], self::statuses($error->getResults())); + $this->assertSame( + array_column($this->body(0)['recipients'], 'idempotency_key'), + array_map(static fn($r): string => $r->getIdempotencyKey(), $error->getResults()) + ); + } + private static function clockThatShutsDownOnSleep(MockClock $clock, Closure $shutDown): ClockInterface { return new class ($clock, $shutDown) implements ClockInterface { From 685605c120d4fe96b1d5eccb67f52adb40a8435c Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:36:58 +0100 Subject: [PATCH 35/44] fix(emails): keep batch keys when the retry wait fails A batch now keeps every recipient's result and key when anything in the retry machinery throws, and the retry wait falls back to a monotonic clock on symfony/clock 6.2, which has no Clock class. A 409 without a readable code leaves recipients unconfirmed. Warnings are deduplicated with a keyed lookup, and the resend advice counts the 24 hours from the key's first use. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- lib/BatchEmailResult.php | 3 +- lib/Emails.php | 21 +++++-- lib/Internal/EmailBatch.php | 13 ++++- test/EmailsBatchTest.php | 73 +++++++++++++++++++++++-- test/EmailsOnOlderSymfonyClocksTest.php | 54 ++++++++++++++---- 6 files changed, 140 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index dffe394..ec0580b 100644 --- a/README.md +++ b/README.md @@ -107,8 +107,8 @@ foreach ($result->getResults() as $email) { - **Recipients.** Each recipient has `to` and optional `distinct_id`, `idempotency_key` and `template_data`. A recipient's `template_data` is merged over the shared `template_data`, and its keys replace the shared ones. With `template_key`, the content is the same for every recipient, so a recipient can't carry `template_data`. A batch takes no `cc`, `bcc`, `attachments` or `scheduled_at`: send those emails with `send()`. - **Requests.** A batch takes 1 to 100 recipients and goes out in one request. The client waits at least 45 seconds for the answer. More than 100 recipients throws `invalid_recipients` before any request. -- **Idempotency keys.** Every retry reuses each recipient's key, so a retry never queues an email twice. Without a key, the client makes one that covers its own retries but not a second call. When a batch may be cut off and run again, pass keys you store: send it again with the same key within 24 hours, so it goes out once. Each recipient of a call needs a different key. Build each key from an ID you store with the job, such as the digest's own ID, never from the time of the run: a retry after midnight would make new keys and send the emails again. Never reuse a key for another email: PostHog sends one email per key, so the other doesn't go out. PostHog usually refuses it with `idempotency_key_reused`, but two sends that arrive at the same time can both answer `queued`. -- **Statuses.** `getStatus()` is `queued` when PostHog accepted the email, `failed` when it refused it (`getError()` says why, such as a suppressed address), and `unconfirmed` when the client can't tell, such as after a lost answer. Send each `unconfirmed` email again with the same key within 24 hours, so it goes out once. `getWarnings()` holds PostHog's warnings. +- **Idempotency keys.** Every retry reuses each recipient's key, so a retry never queues an email twice. Without a key, the client makes one that covers its own retries but not a second call. When a batch may be cut off and run again, pass keys you store: send it again with the same key within 24 hours of its first use, so it goes out once. Each recipient of a call needs a different key. Build each key from an ID you store with the job, such as the digest's own ID, never from the time of the run: a retry after midnight would make new keys and send the emails again. Never reuse a key for another email: PostHog sends one email per key, so the other doesn't go out. PostHog usually refuses it with `idempotency_key_reused`, but two sends that arrive at the same time can both answer `queued`. +- **Statuses.** `getStatus()` is `queued` when PostHog accepted the email, `failed` when it refused it (`getError()` says why, such as a suppressed address), and `unconfirmed` when the client can't tell, such as after a lost answer. Send each `unconfirmed` email again with the same key within 24 hours of its first use, so it goes out once. `getWarnings()` holds PostHog's warnings. - **Errors.** When PostHog refuses the batch as a whole, such as a rate limit past its retries, `batch()` throws `PostHog\EmailBatchError`, whose `getResults()` holds every recipient. `getFix()` carries PostHog's advice. `content_too_large` with status 413 means the request is larger than PostHog takes: send fewer recipients in each batch, or a smaller email. With status 400 it means the content or `template_data` every recipient shares is too large, so fewer recipients won't help: make it smaller, or send those emails one at a time with `send()`. `batch_unavailable` (409) means the project can't send batches yet, and is never retried. `not_found` (404) means the template doesn't exist or batch sends are off. For both, send each email the batch didn't queue with `send()` and its recipient's `idempotency_key`. ## Questions? diff --git a/lib/BatchEmailResult.php b/lib/BatchEmailResult.php index 5229ff0..28a2d99 100644 --- a/lib/BatchEmailResult.php +++ b/lib/BatchEmailResult.php @@ -10,7 +10,8 @@ * - `queued`: PostHog accepted the email. Read its status with Emails::get() to see whether it went out. * - `failed`: PostHog didn't queue the email, and getError() says why, such as a suppressed address. * - `unconfirmed`: the client can't tell whether PostHog queued the email, such as after a lost answer. It may - * still go out. Send it again with the same idempotency key within 24 hours, so it goes out once. + * still go out. Send it again with the same idempotency key within 24 hours of its first use, so it goes out + * once. * getMessageId() is the email's ID when PostHog's answer named one. */ class BatchEmailResult diff --git a/lib/Emails.php b/lib/Emails.php index b2d41f9..dbd5e2b 100644 --- a/lib/Emails.php +++ b/lib/Emails.php @@ -420,9 +420,9 @@ public function get(string $messageId): EmailStatus * Each recipient's `idempotency_key` is 1 to 255 visible ASCII characters, a different one for each recipient * of the call, and every retry reuses it, so a retry never queues an email twice. 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. Build - * each key from an ID you store with the job, such as the digest's own ID, never from the time of the run, so - * a retry after midnight makes the same keys. A single send and a batch recipient + * and run again: a rerun within 24 hours of the first run replays the emails that went out instead of sending + * them twice. Build each key from an ID you store with the job, such as the digest's own ID, never from the time + * of the run, so a retry after midnight makes the same keys. 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 sends one * email per key, so the other doesn't go out. PostHog usually refuses it with `idempotency_key_reused`, but two * sends that arrive at the same time can both answer `queued`. @@ -432,7 +432,8 @@ public function get(string $messageId): EmailStatus * - `queued`: PostHog accepted the email. * - `failed`: PostHog refused it, and getError() says why, such as a suppressed address. * - `unconfirmed`: the client can't tell whether PostHog accepted it, such as after a lost answer, or when - * another request still holds its key. Send it again with the same key within 24 hours, so it goes out once. + * another request still holds its key. Send it again with the same key within 24 hours of its first use, so + * it goes out once. * * When PostHog refuses the batch as a whole, such as a rate limit past its retries, batch() throws * EmailBatchError, whose getResults() holds every recipient: `failed`, or `unconfirmed` when an attempt may have @@ -1157,6 +1158,12 @@ private function sendBatch(EmailBatch $run, string $appHost, string $secretKey, }, $closedBeforeARetry); } catch (EmailError $error) { throw $run->failure($error); + } catch (Throwable $throwable) { + throw $run->failure(new EmailError( + 'client_error', + 'The client failed while sending the batch: ' . $throwable->getMessage(), + previous: $throwable + )); } } @@ -1281,7 +1288,11 @@ private function waitToRetry(int $delayMs, EmailError $error): void private static function forwardOnlyClock(): ClockInterface { - $clock = Clock::get(); + try { + $clock = Clock::get(); + } catch (Throwable) { + return new MonotonicClock(); + } return $clock instanceof NativeClock ? new MonotonicClock() : $clock; } diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index b756837..0b04305 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -18,7 +18,8 @@ final class EmailBatch private const MAX_RECIPIENTS = 100; private const RECIPIENT_FIELDS = ['to', 'distinct_id', 'idempotency_key', 'template_data']; private const UNCONFIRMED_CODES = ['idempotency_key_in_flight', 'delivery_unavailable', 'api_error']; - private const SEND_AGAIN = 'Send it again with the same idempotency_key within 24 hours, so it goes out once.'; + private const SEND_AGAIN = + 'Send it again with the same idempotency_key within 24 hours of its first use, so it goes out once.'; private const IN_FLIGHT = 'idempotency_key_in_flight'; private const JSON_FLAGS = JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE; private const SEND_SINGLY = "send each email the batch didn't queue with emails()->send() and its recipient's " @@ -28,6 +29,8 @@ final class EmailBatch private array $results = []; /** @var list */ private array $warnings = []; + /** @var array */ + private array $warningKeys = []; private bool $mayHaveQueued = false; /** @@ -172,7 +175,9 @@ public function answer(int $status, string $body, array $headers): void $fields = EmailReplies::fields($body); if ($status < 200 || $status >= 300) { $error = self::requestError($fields, $status, $headers); - if ($status >= 500 || ($status === 409 && $error->getErrorCode() === self::IN_FLIGHT)) { + $code = EmailReplies::text($fields['code'] ?? null); + $inFlight = $status === 409 && ($code === null || $code === self::IN_FLIGHT); + if ($status >= 500 || $inFlight) { throw $this->lost($error); } if ($this->mayHaveQueued) { @@ -192,7 +197,9 @@ public function answer(int $status, string $body, array $headers): void $this->settle($index, is_array($slots[$index]) ? $slots[$index] : []); } foreach (EmailReplies::warnings($fields) as $warning) { - if (!in_array($warning, $this->warnings)) { + $key = serialize([$warning->getCode(), $warning->getMessage(), $warning->getFix()]); + if (!isset($this->warningKeys[$key])) { + $this->warningKeys[$key] = true; $this->warnings[] = $warning; } } diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index 0e6eb01..06a510c 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -5,6 +5,7 @@ use Closure; use DateTimeImmutable; use DateTimeZone; +use Error; use JsonSerializable; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; @@ -746,7 +747,7 @@ public function testARecipientARetryRefusesAfterALostAnswerStaysUnconfirmedWithI $this->assertSame( [ 'recipient_suppressed', - 'Send it again with the same idempotency_key within 24 hours, so it goes out once.', + 'Send it again with the same idempotency_key within 24 hours of its first use, so it goes out once.', ], [$second->getError()->getErrorCode(), $second->getError()->getFix()] ); @@ -765,7 +766,7 @@ public function testA503ThenARefusalOfTheWholeRequestKeepsTheRecipientUnconfirme [ 'sending_paused', 422, - 'Send it again with the same idempotency_key within 24 hours, so it goes out once.', + 'Send it again with the same idempotency_key within 24 hours of its first use, so it goes out once.', ], [$result->getError()->getErrorCode(), $result->getError()->getStatusCode(), $result->getError()->getFix()] ); @@ -785,7 +786,8 @@ public function testARecipientPostHogDidNotConfirmIsUnconfirmedWithTheAdviceToSe $result->getMessageId(), $result->getIdempotencyKey(), ]); - $sendAgain = 'Send it again with the same idempotency_key within 24 hours, so it goes out once.'; + $sendAgain = 'Send it again with the same idempotency_key within 24 hours of its first use, ' + . 'so it goes out once.'; $this->assertSame([...$error, $sendAgain], [ $result->getError()->getErrorCode(), $result->getError()->getStatusCode(), @@ -833,7 +835,7 @@ public function testAWholeRequestInFlightAnswerLeavesItsRecipientsUnconfirmed(): [ 'idempotency_key_in_flight', 'Nope.', - 'Send it again with the same idempotency_key within 24 hours, so it goes out once.', + 'Send it again with the same idempotency_key within 24 hours of its first use, so it goes out once.', ], [$recipientError->getErrorCode(), $recipientError->getMessage(), $recipientError->getFix()] ); @@ -921,6 +923,25 @@ public function testAShutdownWhileWaitingToRetryALostAnswerKeepsItsRecipientsUnc ); } + public function testARetryWaitThatThrowsKeepsTheRecipientsUnconfirmedWithTheirKeys(): void + { + Clock::set(self::clockThatShutsDownOnSleep($this->clock, static function (): never { + throw new Error('Class "Symfony\\Component\\Clock\\Clock" not found'); + })); + $this->reply(self::networkError(), self::allQueued()); + + $error = $this->batchError([['to' => 'a@example.com'], ['to' => 'b@example.com']]); + + $this->assertInstanceOf(Error::class, $error->getPrevious()?->getPrevious()); + $this->assertCount(1, $this->requests); + $this->assertSame(['unconfirmed', 'unconfirmed'], self::statuses($error->getResults())); + $this->assertSame( + array_column($this->body(0)['recipients'], 'idempotency_key'), + array_map(static fn($r): string => $r->getIdempotencyKey(), $error->getResults()) + ); + $this->assertSame('delivery_unavailable', $error->getResults()[0]->getError()->getErrorCode()); + } + private static function clockThatShutsDownOnSleep(MockClock $clock, Closure $shutDown): ClockInterface { return new class ($clock, $shutDown) implements ClockInterface { @@ -972,7 +993,11 @@ public function testARefusalOfTheWholeRequestAfterALostAnswerKeepsItsRecipientsU [$result] = $error->getResults(); $this->assertSame(['unconfirmed', null], [$result->getStatus(), $result->getMessageId()]); $this->assertSame( - ['quota_limited', 429, 'Send it again with the same idempotency_key within 24 hours, so it goes out once.'], + [ + 'quota_limited', + 429, + 'Send it again with the same idempotency_key within 24 hours of its first use, so it goes out once.', + ], [$result->getError()->getErrorCode(), $result->getError()->getStatusCode(), $result->getError()->getFix()] ); $this->assertSame([self::BATCH_URL, self::BATCH_URL], $this->requestUrls()); @@ -995,7 +1020,7 @@ public function testALostAnswerAfterTheRetriesTellsEachRecipientToSendAgainWithI ); $this->assertSame( "PostHog didn't confirm this email, so it may still go out. Send it again with the same idempotency_key " - . 'within 24 hours, so it goes out once.', + . 'within 24 hours of its first use, so it goes out once.', $error->getResults()[1]->getError()->getMessage() ); } @@ -1110,6 +1135,42 @@ public function testWarningsReachTheCallerOnce(): void $this->assertSame([self::WARNING_LOGGED], $errorMessages); } + public function testManyDistinctWarningsReachTheCallerInOrderWithoutQuadraticWork(): void + { + $warnings = array_map(static fn(int $index): array => ['code' => "w$index", 'detail' => 'd'], range(0, 19999)); + $this->reply(self::allQueued(['warnings' => [...$warnings, $warnings[0], $warnings[19999]]])); + $started = hrtime(true); + + $result = $this->batch(self::recipients(1)); + + $this->assertLessThan(2000, (hrtime(true) - $started) / 1e6); + $this->assertSame( + array_column($warnings, 'code'), + array_map(static fn($warning): string => $warning->getCode(), $result->getWarnings()) + ); + } + + public static function unreadableInFlightAnswers(): array + { + return [ + 'an empty body' => [''], + 'a body that is not JSON' => ['Conflict'], + ]; + } + + #[DataProvider('unreadableInFlightAnswers')] + public function testA409WithAnUnreadableBodyLeavesItsRecipientsUnconfirmedWithTheirKeys(string $body): void + { + $this->reply([409, $body, []]); + + $error = $this->batchError(self::recipients(2), ['max_retries' => 0]); + + $this->assertSame( + [['unconfirmed', 'key-0'], ['unconfirmed', 'key-1']], + array_map(static fn($r): array => [$r->getStatus(), $r->getIdempotencyKey()], $error->getResults()) + ); + } + public static function setupErrors(): array { return [ diff --git a/test/EmailsOnOlderSymfonyClocksTest.php b/test/EmailsOnOlderSymfonyClocksTest.php index e5f4f9e..e58b744 100644 --- a/test/EmailsOnOlderSymfonyClocksTest.php +++ b/test/EmailsOnOlderSymfonyClocksTest.php @@ -26,17 +26,7 @@ public static function olderClocks(): array #[DataProvider('olderClocks')] public function testAPastTimeQueuedNowIsAnAcceptance(bool $withoutTheClockClass): void { - foreach (spl_autoload_functions() as $loader) { - spl_autoload_unregister($loader); - spl_autoload_register(static function (string $class) use ($loader, $withoutTheClockClass): void { - if ($class === 'Symfony\Component\Clock\NativeClock') { - throw new ErrorException('Implicitly marking parameter $timezone as nullable is deprecated'); - } - if (!$withoutTheClockClass || $class !== 'Symfony\Component\Clock\Clock') { - $loader($class); - } - }); - } + self::loadWithAnOlderClock($withoutTheClockClass); $messageId = '01a18356-c56c-0001-e494-7666bc915188'; $emails = new Emails('phs_secret', 'us.i.posthog.com', transport: static fn(): array => [ 202, @@ -53,4 +43,46 @@ public function testAPastTimeQueuedNowIsAnAcceptance(bool $withoutTheClockClass) $this->assertSame($messageId, $result->getId()); $this->assertSame('queued', $result->getStatus()); } + + #[DataProvider('olderClocks')] + public function testABatchRetriesAfterALostAnswer(bool $withoutTheClockClass): void + { + self::loadWithAnOlderClock($withoutTheClockClass); + $requests = 0; + $emails = new Emails('phs_secret', 'us.i.posthog.com', transport: static function () use (&$requests): array { + $requests++; + + return $requests === 1 ? [503, '', []] : [200, json_encode(['results' => [ + ['message_id' => 'm0', 'status' => 'queued'], + ['message_id' => 'm1', 'status' => 'queued'], + ]]), []]; + }); + + $result = $emails->batch([ + 'recipients' => [['to' => 'a@example.com'], ['to' => 'b@example.com']], + 'template_id' => '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b', + 'max_retries' => 1, + ]); + + $this->assertSame( + ['queued', 'queued'], + array_map(static fn($r): string => $r->getStatus(), $result->getResults()) + ); + $this->assertSame(2, $requests); + } + + private static function loadWithAnOlderClock(bool $withoutTheClockClass): void + { + foreach (spl_autoload_functions() as $loader) { + spl_autoload_unregister($loader); + spl_autoload_register(static function (string $class) use ($loader, $withoutTheClockClass): void { + if ($class === 'Symfony\Component\Clock\NativeClock') { + throw new ErrorException('Implicitly marking parameter $timezone as nullable is deprecated'); + } + if (!$withoutTheClockClass || $class !== 'Symfony\Component\Clock\Clock') { + $loader($class); + } + }); + } + } } From cbbaae3de21ae04df771a6b3dfa5c4d1ca8b0055 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:50:42 +0100 Subject: [PATCH 36/44] fix(emails): keep a batch unconfirmed when reading a lost answer throws A 503 or in-flight 409 now marks the batch as possibly queued before it reads the answer, so a Retry-After that throws while parsing leaves the recipients unconfirmed with their keys. The retry wait falls back to usleep when symfony/clock 6.2.0 can't build a MonotonicClock either. Co-Authored-By: Claude Opus 5.5 --- lib/Emails.php | 21 ++++++++--- lib/Internal/EmailBatch.php | 6 ++- test/EmailsBatchTest.php | 50 ++++++++++++++++++++++++- test/EmailsOnOlderSymfonyClocksTest.php | 22 +++++++---- 4 files changed, 82 insertions(+), 17 deletions(-) diff --git a/lib/Emails.php b/lib/Emails.php index dbd5e2b..842b852 100644 --- a/lib/Emails.php +++ b/lib/Emails.php @@ -1274,27 +1274,36 @@ private function withRetries(int $maxRetries, Closure $attemptOnce, ?EmailError private function waitToRetry(int $delayMs, EmailError $error): void { $clock = self::forwardOnlyClock(); - $start = $clock->now(); + $startedNs = hrtime(true); + $start = $clock?->now(); while (!($this->isClosed)()) { - $remainingUs = $delayMs * 1000 - self::microsecondsBetween($start, $clock->now()); + $elapsedUs = $clock === null + ? intdiv(hrtime(true) - $startedNs, 1000) + : self::microsecondsBetween($start, $clock->now()); + $remainingUs = $delayMs * 1000 - $elapsedUs; if ($remainingUs <= 0) { return; } - $clock->sleep($remainingUs / 1_000_000); + $clock === null ? usleep($remainingUs) : $clock->sleep($remainingUs / 1_000_000); } throw $error; } - private static function forwardOnlyClock(): ClockInterface + private static function forwardOnlyClock(): ?ClockInterface { try { $clock = Clock::get(); + if (!$clock instanceof NativeClock) { + return $clock; + } } catch (Throwable) { + } + try { return new MonotonicClock(); + } catch (Throwable) { + return null; } - - return $clock instanceof NativeClock ? new MonotonicClock() : $clock; } private static function microsecondsBetween(DateTimeImmutable $start, DateTimeImmutable $end): int diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index 0b04305..2306529 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -174,12 +174,14 @@ public function answer(int $status, string $body, array $headers): void { $fields = EmailReplies::fields($body); if ($status < 200 || $status >= 300) { - $error = self::requestError($fields, $status, $headers); $code = EmailReplies::text($fields['code'] ?? null); $inFlight = $status === 409 && ($code === null || $code === self::IN_FLIGHT); if ($status >= 500 || $inFlight) { - throw $this->lost($error); + $this->mayHaveQueued = true; + $this->setAll('unconfirmed', self::unconfirmed(null)); + throw $this->lost(self::requestError($fields, $status, $headers)); } + $error = self::requestError($fields, $status, $headers); if ($this->mayHaveQueued) { $this->setAll('unconfirmed', self::sendAgain($error, self::SEND_AGAIN)); } diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index 06a510c..7a077a2 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -932,7 +932,7 @@ public function testARetryWaitThatThrowsKeepsTheRecipientsUnconfirmedWithTheirKe $error = $this->batchError([['to' => 'a@example.com'], ['to' => 'b@example.com']]); - $this->assertInstanceOf(Error::class, $error->getPrevious()?->getPrevious()); + $this->assertSame('client_error', $error->getErrorCode()); $this->assertCount(1, $this->requests); $this->assertSame(['unconfirmed', 'unconfirmed'], self::statuses($error->getResults())); $this->assertSame( @@ -942,6 +942,54 @@ public function testARetryWaitThatThrowsKeepsTheRecipientsUnconfirmedWithTheirKe $this->assertSame('delivery_unavailable', $error->getResults()[0]->getError()->getErrorCode()); } + public static function answersThatMayHaveQueued(): array + { + return [ + 'a 503' => [503, ''], + 'an in-flight 409' => [409, '{"code":"idempotency_key_in_flight","detail":"Nope."}'], + ]; + } + + #[DataProvider('answersThatMayHaveQueued')] + public function testAnAnswerThatMayHaveQueuedKeepsItsRecipientsUnconfirmedWhenReadingItThrows( + int $status, + string $body + ): void { + Clock::set(new class ($this->clock, fn(): bool => $this->requests !== []) implements ClockInterface { + public function __construct(private MockClock $clock, private Closure $afterTheRequest) + { + } + + public function now(): DateTimeImmutable + { + if (($this->afterTheRequest)()) { + throw new Error('The clock failed.'); + } + + return $this->clock->now(); + } + + public function sleep(float|int $seconds): void + { + $this->clock->sleep($seconds); + } + + public function withTimeZone(DateTimeZone|string $timezone): static + { + return $this; + } + }); + $this->reply([$status, $body, ['Retry-After: Wed, 21 Oct 2026 07:28:00 GMT']]); + + $error = $this->batchError(self::recipients(2)); + + $this->assertCount(1, $this->requests); + $this->assertSame( + [['unconfirmed', 'key-0'], ['unconfirmed', 'key-1']], + array_map(static fn($r): array => [$r->getStatus(), $r->getIdempotencyKey()], $error->getResults()) + ); + } + private static function clockThatShutsDownOnSleep(MockClock $clock, Closure $shutDown): ClockInterface { return new class ($clock, $shutDown) implements ClockInterface { diff --git a/test/EmailsOnOlderSymfonyClocksTest.php b/test/EmailsOnOlderSymfonyClocksTest.php index e58b744..909b49d 100644 --- a/test/EmailsOnOlderSymfonyClocksTest.php +++ b/test/EmailsOnOlderSymfonyClocksTest.php @@ -20,13 +20,14 @@ public static function olderClocks(): array return [ 'symfony/clock 6.2' => [true], 'symfony/clock 6.3.0' => [false], + 'symfony/clock 6.2.0 on PHP 8.4, whose MonotonicClock raises a deprecation' => [true, true], ]; } #[DataProvider('olderClocks')] - public function testAPastTimeQueuedNowIsAnAcceptance(bool $withoutTheClockClass): void + public function testAPastTimeQueuedNowIsAnAcceptance(bool $withoutTheClockClass, bool $monotonicFails = false): void { - self::loadWithAnOlderClock($withoutTheClockClass); + self::loadWithAnOlderClock($withoutTheClockClass, $monotonicFails); $messageId = '01a18356-c56c-0001-e494-7666bc915188'; $emails = new Emails('phs_secret', 'us.i.posthog.com', transport: static fn(): array => [ 202, @@ -45,9 +46,9 @@ public function testAPastTimeQueuedNowIsAnAcceptance(bool $withoutTheClockClass) } #[DataProvider('olderClocks')] - public function testABatchRetriesAfterALostAnswer(bool $withoutTheClockClass): void + public function testABatchRetriesAfterALostAnswer(bool $withoutTheClockClass, bool $monotonicFails = false): void { - self::loadWithAnOlderClock($withoutTheClockClass); + self::loadWithAnOlderClock($withoutTheClockClass, $monotonicFails); $requests = 0; $emails = new Emails('phs_secret', 'us.i.posthog.com', transport: static function () use (&$requests): array { $requests++; @@ -71,15 +72,20 @@ public function testABatchRetriesAfterALostAnswer(bool $withoutTheClockClass): v $this->assertSame(2, $requests); } - private static function loadWithAnOlderClock(bool $withoutTheClockClass): void + private static function loadWithAnOlderClock(bool $withoutTheClockClass, bool $monotonicFails): void { foreach (spl_autoload_functions() as $loader) { spl_autoload_unregister($loader); - spl_autoload_register(static function (string $class) use ($loader, $withoutTheClockClass): void { - if ($class === 'Symfony\Component\Clock\NativeClock') { + $deprecated = ['Symfony\Component\Clock\NativeClock']; + if ($monotonicFails) { + $deprecated[] = 'Symfony\Component\Clock\MonotonicClock'; + } + $without = $withoutTheClockClass; + spl_autoload_register(static function (string $class) use ($loader, $without, $deprecated): void { + if (in_array($class, $deprecated, true)) { throw new ErrorException('Implicitly marking parameter $timezone as nullable is deprecated'); } - if (!$withoutTheClockClass || $class !== 'Symfony\Component\Clock\Clock') { + if (!$without || $class !== 'Symfony\Component\Clock\Clock') { $loader($class); } }); From f03ff9b930dfcfb3d49e094fee084e6dc2605f6d Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:04:07 +0100 Subject: [PATCH 37/44] fix(emails): keep batch warnings and retry waits portable Warning dedupe keys on nested arrays instead of serialize(), so an app that disables serialize() keeps PostHog's queued results. The fallback retry wait reads hrtime() as seconds and nanoseconds, so a wait longer than two seconds doesn't overflow on 32-bit PHP. Co-Authored-By: Claude Opus 5.5 --- lib/Emails.php | 14 ++++++++++++-- lib/Internal/EmailBatch.php | 9 +++++---- test/EmailsBatchTest.php | 38 +++++++++++++++++++++++++++++++------ 3 files changed, 49 insertions(+), 12 deletions(-) diff --git a/lib/Emails.php b/lib/Emails.php index 842b852..7e9bb30 100644 --- a/lib/Emails.php +++ b/lib/Emails.php @@ -1274,11 +1274,11 @@ private function withRetries(int $maxRetries, Closure $attemptOnce, ?EmailError private function waitToRetry(int $delayMs, EmailError $error): void { $clock = self::forwardOnlyClock(); - $startedNs = hrtime(true); + $started = hrtime(); $start = $clock?->now(); while (!($this->isClosed)()) { $elapsedUs = $clock === null - ? intdiv(hrtime(true) - $startedNs, 1000) + ? self::microsecondsSince($started) : self::microsecondsBetween($start, $clock->now()); $remainingUs = $delayMs * 1000 - $elapsedUs; if ($remainingUs <= 0) { @@ -1306,6 +1306,16 @@ private static function forwardOnlyClock(): ?ClockInterface } } + /** + * @param array{int, int} $started + */ + private static function microsecondsSince(array $started): int + { + [$seconds, $nanoseconds] = hrtime(); + + return ($seconds - $started[0]) * 1_000_000 + intdiv($nanoseconds - $started[1], 1000); + } + private static function microsecondsBetween(DateTimeImmutable $start, DateTimeImmutable $end): int { $seconds = (int) (self::wholeEpochSecondsAsFloat($end) - self::wholeEpochSecondsAsFloat($start)); diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index 2306529..d03073a 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -29,7 +29,7 @@ final class EmailBatch private array $results = []; /** @var list */ private array $warnings = []; - /** @var array */ + /** @var array>> */ private array $warningKeys = []; private bool $mayHaveQueued = false; @@ -199,9 +199,10 @@ public function answer(int $status, string $body, array $headers): void $this->settle($index, is_array($slots[$index]) ? $slots[$index] : []); } foreach (EmailReplies::warnings($fields) as $warning) { - $key = serialize([$warning->getCode(), $warning->getMessage(), $warning->getFix()]); - if (!isset($this->warningKeys[$key])) { - $this->warningKeys[$key] = true; + $fix = $warning->getFix(); + $fixKey = $fix === null ? 0 : "s$fix"; + if (!isset($this->warningKeys[$warning->getCode()][$warning->getMessage()][$fixKey])) { + $this->warningKeys[$warning->getCode()][$warning->getMessage()][$fixKey] = true; $this->warnings[] = $warning; } } diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index 7a077a2..8c0423a 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -524,7 +524,7 @@ public function testARecipientIsEncodedWithoutExtraCopiesOfItsData(): void echo $result->getResults()[0]->getStatus(), ' ', $result->getResults()[0]->getError()->getErrorCode(); PHP; - $this->assertSame([0, 'failed content_too_large'], self::runWithMemoryLimit($script, '32M')); + $this->assertSame([0, 'failed content_too_large'], self::runWithPhpOptions($script, '-d memory_limit=32M')); } #[DataProvider('recipientsNearTheBodyLimit')] @@ -566,7 +566,7 @@ public function testAHundredRecipientsNearTheBodyLimitGoOutInTightMemory(int $ea PHP; try { - $this->assertSame([0, '100 body sent'], self::runWithMemoryLimit($script, '32M')); + $this->assertSame([0, '100 body sent'], self::runWithPhpOptions($script, '-d memory_limit=32M')); $request = json_decode(file_get_contents($bodyFile), true, flags: JSON_THROW_ON_ERROR); } finally { unlink($bodyFile); @@ -608,7 +608,7 @@ public function testSharedDataTooLargeForPostHogComesBackAsItsRefusalInTightMemo } PHP; - $this->assertSame([0, 'content_too_large'], self::runWithMemoryLimit($script, '32M')); + $this->assertSame([0, 'content_too_large'], self::runWithPhpOptions($script, '-d memory_limit=32M')); } #[DataProvider('laterSerializations')] @@ -686,18 +686,21 @@ public function testARecipientWithoutToIsRefusedBeforeSharedContentIsEncoded(): } PHP; - $this->assertSame([0, '["invalid_recipient","recipients__0__to"]'], self::runWithMemoryLimit($script, '128M')); + $this->assertSame( + [0, '["invalid_recipient","recipients__0__to"]'], + self::runWithPhpOptions($script, '-d memory_limit=128M') + ); } /** * @return array{int, string} */ - private static function runWithMemoryLimit(string $code, string $limit): array + private static function runWithPhpOptions(string $code, string $options): array { $script = tempnam(sys_get_temp_dir(), 'posthog-emails-batch-'); file_put_contents($script, $code); try { - $command = escapeshellarg(PHP_BINARY) . " -d memory_limit=$limit " . escapeshellarg($script) . ' ' + $command = escapeshellarg(PHP_BINARY) . " $options " . escapeshellarg($script) . ' ' . escapeshellarg(__DIR__ . '/../vendor/autoload.php') . ' 2>&1'; exec($command, $output, $exitCode); @@ -1198,6 +1201,29 @@ public function testManyDistinctWarningsReachTheCallerInOrderWithoutQuadraticWor ); } + public function testAQueuedAnswerWithWarningsKeepsItsResultsWhenSerializeIsDisabled(): void + { + $script = <<<'PHP' + [200, json_encode([ + 'results' => [['message_id' => 'm0', 'status' => 'queued']], + 'warnings' => [['code' => 'unverified_link', 'detail' => 'A link points to an unknown domain.']], +]), []]); +$result = $emails->batch([ + 'recipients' => [['to' => 'a@example.com']], + 'template_id' => '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b', +]); +$recipient = $result->getResults()[0]; +echo json_encode([$recipient->getStatus(), $recipient->getMessageId(), count($result->getWarnings())]); +PHP; + + $this->assertSame( + [0, '["queued","m0",1]'], + self::runWithPhpOptions($script, '-d disable_functions=serialize -d error_log=/dev/null') + ); + } + public static function unreadableInFlightAnswers(): array { return [ From 7d94ee4ceb8ff42d705b80f1229c17043c7a6914 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:05:35 +0100 Subject: [PATCH 38/44] fix(emails): name a 409 batch_unavailable a validation error A project without batch sends isn't a request still in progress, so its error name matches Python's validation_error. Co-Authored-By: Claude Opus 5.5 --- lib/EmailError.php | 4 +++- test/EmailsBatchTest.php | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/lib/EmailError.php b/lib/EmailError.php index 3da7928..3ea2f08 100644 --- a/lib/EmailError.php +++ b/lib/EmailError.php @@ -184,7 +184,9 @@ private static function nameFor(?int $status, string $code): string 400 => 'validation_error', 403 => 'invalid_permission', 404 => 'not_found', - 409 => $code === 'template_outdated' ? 'validation_error' : 'concurrent_idempotent_requests', + 409 => in_array($code, ['template_outdated', 'batch_unavailable'], true) + ? 'validation_error' + : 'concurrent_idempotent_requests', 422 => $code === 'idempotency_key_reused' ? 'invalid_idempotent_request' : 'validation_error', 429 => $code === 'quota_limited' ? 'monthly_quota_exceeded' : 'rate_limit_exceeded', 503 => 'service_unavailable', diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index 8c0423a..c34bc84 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -1107,6 +1107,7 @@ public function testBatchUnavailableIsNotRetriedAndSaysToSendEachEmailOnItsOwn() $this->assertCount(1, $this->requests); $this->assertSame('batch_unavailable', $error->getErrorCode()); + $this->assertSame('validation_error', $error->getErrorName()); $this->assertSame('Until batch sends are on for the project, ' . self::SEND_SINGLY, $error->getFix()); $this->assertSame(['failed', 'failed'], self::statuses($error->getResults())); } From 6dcfb43864ea5f55cd1ad62bac4a6f95959dbbab Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:17:09 +0100 Subject: [PATCH 39/44] fix(emails): keep a batch unconfirmed when the client fails mid-send Anything the client throws while it sends a batch, such as a disabled curl function after the request went out, now leaves every recipient unconfirmed with its key instead of failed. A recipient's template_data gets the same JSON depth as a single send, and the retry wait calls hrtime() only when no clock is available. Co-Authored-By: Claude Opus 5.5 --- lib/Emails.php | 6 ++--- lib/Internal/EmailBatch.php | 3 ++- test/EmailsBatchTest.php | 54 +++++++++++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+), 4 deletions(-) diff --git a/lib/Emails.php b/lib/Emails.php index 7e9bb30..50e8571 100644 --- a/lib/Emails.php +++ b/lib/Emails.php @@ -1159,11 +1159,11 @@ private function sendBatch(EmailBatch $run, string $appHost, string $secretKey, } catch (EmailError $error) { throw $run->failure($error); } catch (Throwable $throwable) { - throw $run->failure(new EmailError( + throw $run->failure($run->lost(new EmailError( 'client_error', 'The client failed while sending the batch: ' . $throwable->getMessage(), previous: $throwable - )); + ))); } } @@ -1274,7 +1274,7 @@ private function withRetries(int $maxRetries, Closure $attemptOnce, ?EmailError private function waitToRetry(int $delayMs, EmailError $error): void { $clock = self::forwardOnlyClock(); - $started = hrtime(); + $started = $clock === null ? hrtime() : null; $start = $clock?->now(); while (!($this->isClosed)()) { $elapsedUs = $clock === null diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index d03073a..8f3d8aa 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -22,6 +22,7 @@ final class EmailBatch 'Send it again with the same idempotency_key within 24 hours of its first use, so it goes out once.'; private const IN_FLIGHT = 'idempotency_key_in_flight'; private const JSON_FLAGS = JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE; + private const JSON_DEPTH = 514; private const SEND_SINGLY = "send each email the batch didn't queue with emails()->send() and its recipient's " . 'idempotency_key.'; @@ -82,7 +83,7 @@ public static function prepare(array $shared, mixed $recipients): self } $request = [...$shared, 'recipients' => $wires]; try { - return new self($members, json_encode($request, self::JSON_FLAGS)); + return new self($members, json_encode($request, self::JSON_FLAGS, self::JSON_DEPTH)); } catch (JsonException $exception) { throw new EmailError( 'invalid_form', diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index c34bc84..35f9b73 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -1225,6 +1225,60 @@ public function testAQueuedAnswerWithWarningsKeepsItsResultsWhenSerializeIsDisab ); } + public function testATransportThatThrowsKeepsTheRecipientsUnconfirmedWithTheirKeys(): void + { + $this->reply(static function (): never { + throw new RuntimeException('curl_getinfo() has been disabled for security reasons'); + }); + + $error = $this->batchError(self::recipients(2)); + + $this->assertSame('client_error', $error->getErrorCode()); + $this->assertCount(1, $this->requests); + $this->assertSame( + [['unconfirmed', 'key-0'], ['unconfirmed', 'key-1']], + array_map(static fn($r): array => [$r->getStatus(), $r->getIdempotencyKey()], $error->getResults()) + ); + } + + public function testARecipientsDataAsDeepAsASingleSendAllowsGoesOut(): void + { + $data = 1; + for ($level = 0; $level < 510; $level++) { + $data = [$data]; + } + $this->reply(self::ok(self::queued('m0'))); + + $result = $this->batch([['to' => 'a@example.com', 'template_data' => ['deep' => $data]]]); + + $this->assertSame(['queued'], self::statuses($result->getResults())); + } + + public function testARetryWaitOnAWorkingClockNeedsNoHrtime(): void + { + $script = <<<'PHP' + [ + ['message_id' => 'm0', 'status' => 'queued'], + ]]), []]; +}); +$result = $emails->batch([ + 'recipients' => [['to' => 'a@example.com']], + 'template_id' => '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b', + 'max_retries' => 1, +]); +echo json_encode([$result->getResults()[0]->getStatus(), $requests]); +PHP; + + $this->assertSame([0, '["queued",2]'], self::runWithPhpOptions($script, '-d disable_functions=hrtime')); + } + public static function unreadableInFlightAnswers(): array { return [ From 436bc105d58e8d1dfa1a726040146452a1cd31c0 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:27:29 +0100 Subject: [PATCH 40/44] fix(emails): keep PostHog's in-flight answer when a batch retry fails A client failure after a recorded in-flight or lost answer no longer replaces each recipient's error with a generic one, so the caller keeps PostHog's code and fix. Co-Authored-By: Claude Opus 5.5 --- lib/Emails.php | 4 ++-- lib/Internal/EmailBatch.php | 9 +++++++++ test/EmailsBatchTest.php | 29 ++++++++++++++++++++++++++++- 3 files changed, 39 insertions(+), 3 deletions(-) diff --git a/lib/Emails.php b/lib/Emails.php index 50e8571..7166668 100644 --- a/lib/Emails.php +++ b/lib/Emails.php @@ -1159,11 +1159,11 @@ private function sendBatch(EmailBatch $run, string $appHost, string $secretKey, } catch (EmailError $error) { throw $run->failure($error); } catch (Throwable $throwable) { - throw $run->failure($run->lost(new EmailError( + throw $run->interrupted(new EmailError( 'client_error', 'The client failed while sending the batch: ' . $throwable->getMessage(), previous: $throwable - ))); + )); } } diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index 8f3d8aa..912f39e 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -233,6 +233,15 @@ public function result(): SendBatchResult return new SendBatchResult($this->outcome(), $this->warnings); } + public function interrupted(EmailError $error): EmailBatchError + { + if (!$this->mayHaveQueued) { + $this->lost($error); + } + + return $this->failure($error); + } + public function failure(EmailError $error): EmailBatchError { if (!$this->mayHaveQueued) { diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index 35f9b73..416c5b8 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -945,6 +945,29 @@ public function testARetryWaitThatThrowsKeepsTheRecipientsUnconfirmedWithTheirKe $this->assertSame('delivery_unavailable', $error->getResults()[0]->getError()->getErrorCode()); } + public function testARetryWaitThatThrowsAfterAnInFlightAnswerKeepsPostHogsAnswerOnItsRecipients(): void + { + Clock::set(self::clockThatShutsDownOnSleep($this->clock, static function (): never { + throw new Error('The clock failed.'); + })); + $this->reply(self::wholeCall(409, 'idempotency_key_in_flight'), self::allQueued()); + + $error = $this->batchError(self::recipients(2)); + + $this->assertSame('client_error', $error->getErrorCode()); + $this->assertCount(1, $this->requests); + $this->assertSame( + [ + ['unconfirmed', 'key-0', 'idempotency_key_in_flight'], + ['unconfirmed', 'key-1', 'idempotency_key_in_flight'], + ], + array_map( + static fn($r): array => [$r->getStatus(), $r->getIdempotencyKey(), $r->getError()?->getErrorCode()], + $error->getResults() + ) + ); + } + public static function answersThatMayHaveQueued(): array { return [ @@ -1228,7 +1251,7 @@ public function testAQueuedAnswerWithWarningsKeepsItsResultsWhenSerializeIsDisab public function testATransportThatThrowsKeepsTheRecipientsUnconfirmedWithTheirKeys(): void { $this->reply(static function (): never { - throw new RuntimeException('curl_getinfo() has been disabled for security reasons'); + throw new Error('Call to undefined function curl_getinfo()'); }); $error = $this->batchError(self::recipients(2)); @@ -1252,6 +1275,10 @@ public function testARecipientsDataAsDeepAsASingleSendAllowsGoesOut(): void $result = $this->batch([['to' => 'a@example.com', 'template_data' => ['deep' => $data]]]); $this->assertSame(['queued'], self::statuses($result->getResults())); + $this->assertStringContainsString( + '"message_data":{"deep":' . json_encode($data) . '}', + (string) $this->requests[0]['body'] + ); } public function testARetryWaitOnAWorkingClockNeedsNoHrtime(): void From 240916a1c3dbb081e9d4ae88880dba9416065321 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:06:25 +0100 Subject: [PATCH 41/44] fix(emails): point a batch 404 without a field at the template ID PostHog answers the same 404 for an unknown template_id and for a project without batch sends, so the error no longer blames the server. It says to check template_id, and if it's right, to send each recipient on its own until batch sends are available. A template_key batch says batch sends from code aren't available. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- lib/Emails.php | 8 +++-- lib/Internal/EmailBatch.php | 43 ++++++++++++++++------ test/EmailsBatchTest.php | 71 ++++++++++++++++++++++++++++++++----- 4 files changed, 102 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index ec0580b..9152c00 100644 --- a/README.md +++ b/README.md @@ -109,7 +109,7 @@ foreach ($result->getResults() as $email) { - **Requests.** A batch takes 1 to 100 recipients and goes out in one request. The client waits at least 45 seconds for the answer. More than 100 recipients throws `invalid_recipients` before any request. - **Idempotency keys.** Every retry reuses each recipient's key, so a retry never queues an email twice. Without a key, the client makes one that covers its own retries but not a second call. When a batch may be cut off and run again, pass keys you store: send it again with the same key within 24 hours of its first use, so it goes out once. Each recipient of a call needs a different key. Build each key from an ID you store with the job, such as the digest's own ID, never from the time of the run: a retry after midnight would make new keys and send the emails again. Never reuse a key for another email: PostHog sends one email per key, so the other doesn't go out. PostHog usually refuses it with `idempotency_key_reused`, but two sends that arrive at the same time can both answer `queued`. - **Statuses.** `getStatus()` is `queued` when PostHog accepted the email, `failed` when it refused it (`getError()` says why, such as a suppressed address), and `unconfirmed` when the client can't tell, such as after a lost answer. Send each `unconfirmed` email again with the same key within 24 hours of its first use, so it goes out once. `getWarnings()` holds PostHog's warnings. -- **Errors.** When PostHog refuses the batch as a whole, such as a rate limit past its retries, `batch()` throws `PostHog\EmailBatchError`, whose `getResults()` holds every recipient. `getFix()` carries PostHog's advice. `content_too_large` with status 413 means the request is larger than PostHog takes: send fewer recipients in each batch, or a smaller email. With status 400 it means the content or `template_data` every recipient shares is too large, so fewer recipients won't help: make it smaller, or send those emails one at a time with `send()`. `batch_unavailable` (409) means the project can't send batches yet, and is never retried. `not_found` (404) means the template doesn't exist or batch sends are off. For both, send each email the batch didn't queue with `send()` and its recipient's `idempotency_key`. +- **Errors.** When PostHog refuses the batch as a whole, such as a rate limit past its retries, `batch()` throws `PostHog\EmailBatchError`, whose `getResults()` holds every recipient. `getFix()` carries PostHog's advice. `content_too_large` with status 413 means the request is larger than PostHog takes: send fewer recipients in each batch, or a smaller email. With status 400 it means the content or `template_data` every recipient shares is too large, so fewer recipients won't help: make it smaller, or send those emails one at a time with `send()`. `batch_unavailable` (409) means the project can't send batches yet, and is never retried: send each email the batch didn't queue with `send()` and its recipient's `idempotency_key`. `not_found` (404) without a field means PostHog found no template with that `template_id`, or batch sends aren't available for the project. Check the `template_id`. If it's right, send each recipient on its own with `send()` and its `idempotency_key` until batch sends are available. ## Questions? diff --git a/lib/Emails.php b/lib/Emails.php index 7166668..c82dd79 100644 --- a/lib/Emails.php +++ b/lib/Emails.php @@ -441,9 +441,11 @@ public function get(string $messageId): EmailStatus * is larger than PostHog takes: send fewer recipients in each batch, or a smaller email. With status 400 it means * the content or template_data every recipient shares is too large, so fewer recipients won't help: make it * smaller, or send those emails one at a time with send(). - * `batch_unavailable` (409) means the project can't send batches yet, and is never retried. - * `not_found` (404) means the template doesn't exist or batch sends are off for the project. For both, send each - * email the batch didn't queue with send() and its recipient's `idempotency_key`. + * `batch_unavailable` (409) means the project can't send batches yet, and is never retried. Send each email the + * batch didn't queue with send() and its recipient's `idempotency_key`. + * `not_found` (404) without a field means PostHog found no template with that `template_id`, or batch sends + * aren't available for the project. Check the `template_id`. If it's right, send each recipient on its own with + * send() and its `idempotency_key` until batch sends are available. * * ```php * $result = $client->emails()->batch([ diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index 912f39e..7e02f49 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -25,6 +25,8 @@ final class EmailBatch private const JSON_DEPTH = 514; private const SEND_SINGLY = "send each email the batch didn't queue with emails()->send() and its recipient's " . 'idempotency_key.'; + private const SEND_EACH_ON_ITS_OWN = 'send each recipient on its own with emails()->send() and its ' + . 'idempotency_key until batch sends are available.'; /** @var array */ private array $results = []; @@ -37,7 +39,7 @@ final class EmailBatch /** * @param list $members */ - private function __construct(private array $members, private string $body) + private function __construct(private array $members, private string $body, private bool $isTemplateForm) { } @@ -83,7 +85,11 @@ public static function prepare(array $shared, mixed $recipients): self } $request = [...$shared, 'recipients' => $wires]; try { - return new self($members, json_encode($request, self::JSON_FLAGS, self::JSON_DEPTH)); + return new self( + $members, + json_encode($request, self::JSON_FLAGS, self::JSON_DEPTH), + $isTemplateForm + ); } catch (JsonException $exception) { throw new EmailError( 'invalid_form', @@ -180,9 +186,9 @@ public function answer(int $status, string $body, array $headers): void if ($status >= 500 || $inFlight) { $this->mayHaveQueued = true; $this->setAll('unconfirmed', self::unconfirmed(null)); - throw $this->lost(self::requestError($fields, $status, $headers)); + throw $this->lost($this->requestError($fields, $status, $headers)); } - $error = self::requestError($fields, $status, $headers); + $error = $this->requestError($fields, $status, $headers); if ($this->mayHaveQueued) { $this->setAll('unconfirmed', self::sendAgain($error, self::SEND_AGAIN)); } @@ -294,15 +300,21 @@ private function set( * @param array $fields * @param list $headers */ - private static function requestError(array $fields, int $status, array $headers): EmailError + private function requestError(array $fields, int $status, array $headers): EmailError { $answered = array_filter($fields, static fn($value): bool => $value !== null); - if ($status === 404) { - $answered += [ + if ($status === 404 && self::namesNoField($answered)) { + $answered = [ + ...array_diff_key($answered, ['why' => true]), 'code' => 'not_found', - 'detail' => 'PostHog found no batch send for this request, so no email was sent.', - 'why' => "The template doesn't exist, or batch sends are off for this project or this PostHog version.", - 'fix' => 'Check template_id, or ' . self::SEND_SINGLY, + 'detail' => $this->isTemplateForm + ? "PostHog found no template with this template_id, or batch sends aren't available for this " + . 'project, so it sent no email of this request.' + : "Batch sends from code aren't available for this project, so PostHog sent no email of this " + . 'request.', + 'fix' => $this->isTemplateForm + ? "Check template_id. If it's right, " . self::SEND_EACH_ON_ITS_OWN + : ucfirst(self::SEND_EACH_ON_ITS_OWN), ]; } if ($status === 413) { @@ -316,6 +328,17 @@ private static function requestError(array $fields, int $status, array $headers) return EmailReplies::error($answered, $status, $headers); } + /** + * @param array $answered + */ + private static function namesNoField(array $answered): bool + { + $code = EmailReplies::text($answered['code'] ?? null); + + return EmailReplies::text($answered['attr'] ?? null) === null + && in_array($code, [null, 'not_found', 'api_error'], true); + } + private static function slotError(mixed $error, ?string $messageId): EmailError { if (!is_array($error)) { diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index 416c5b8..c049229 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -30,6 +30,8 @@ class EmailsBatchTest extends TestCase private const WARNING_LOGGED = '[PostHog][Emails] Email warning sandbox_sender: Sent from the test sender.'; private const SEND_SINGLY = "send each email the batch didn't queue with emails()->send() and its recipient's " . 'idempotency_key.'; + private const SEND_EACH_ON_ITS_OWN = 'send each recipient on its own with emails()->send() and its ' + . 'idempotency_key until batch sends are available.'; private bool $closed = false; @@ -1135,24 +1137,77 @@ public function testBatchUnavailableIsNotRetriedAndSaysToSendEachEmailOnItsOwn() $this->assertSame(['failed', 'failed'], self::statuses($error->getResults())); } - public static function notFoundAnswers(): array + public static function notFoundAnswersWithoutAField(): array { return [ - 'empty body' => ['', 'PostHog found no batch send for this request, so no email was sent.'], - "PostHog's answer" => ['{"type":"invalid_request","code":"not_found","detail":"Not found."}', 'Not found.'], + 'empty body' => [''], + 'unknown template or batch sends off' => [ + '{"type":"invalid_request","code":"not_found","detail":"Not found.","attr":null}', + ], + 'no batch route' => ['{"type":"invalid_request","code":"not_found","detail":"Endpoint not found."}'], + 'blank code' => ['{"code":"","detail":"Not found."}'], + 'generic code' => ['{"code":"api_error"}'], ]; } - #[DataProvider('notFoundAnswers')] - public function testA404SaysBatchSendsAreUnavailable(string $body, string $message): void + #[DataProvider('notFoundAnswersWithoutAField')] + public function testA404WithoutAFieldOnATemplateBatchSaysToCheckTheTemplateId(string $body): void + { + $this->reply([404, $body, []]); + + $error = $this->batchError(self::recipients(2)); + + $this->assertSame(['not_found', 404], [$error->getErrorCode(), $error->getStatusCode()]); + $this->assertSame( + "PostHog found no template with this template_id, or batch sends aren't available for this project, " + . 'so it sent no email of this request.', + $error->getMessage() + ); + $this->assertSame( + "Check template_id. If it's right, " . self::SEND_EACH_ON_ITS_OWN, + $error->getFix() + ); + $this->assertNull($error->getWhy()); + $this->assertSame(['failed', 'failed'], self::statuses($error->getResults())); + } + + #[DataProvider('notFoundAnswersWithoutAField')] + public function testA404WithoutAFieldOnACodeBatchSaysToSendEachRecipientOnItsOwn(string $body): void { $this->reply([404, $body, []]); + try { + $this->emails()->batch([ + 'template_key' => 'digest', + 'subject' => 'Hi', + 'html' => '

Hi

', + 'recipients' => self::recipients(1), + ]); + $this->fail('batch() did not throw EmailBatchError'); + } catch (EmailBatchError $error) { + } + + $this->assertSame(['not_found', 404], [$error->getErrorCode(), $error->getStatusCode()]); + $this->assertSame( + "Batch sends from code aren't available for this project, so PostHog sent no email of this request.", + $error->getMessage() + ); + $this->assertSame(ucfirst(self::SEND_EACH_ON_ITS_OWN), $error->getFix()); + $this->assertNull($error->getWhy()); + $this->assertSame(['failed'], self::statuses($error->getResults())); + } + + public function testA404ThatNamesAFieldKeepsPostHogsAnswer(): void + { + $this->reply([404, '{"type":"invalid_request","code":"not_found","detail":"Template is archived.",' + . '"attr":"template_id"}', []]); + $error = $this->batchError(self::recipients(1)); - $this->assertSame(['not_found', $message], [$error->getErrorCode(), $error->getMessage()]); - $this->assertStringContainsString('batch sends', strtolower((string) $error->getWhy())); - $this->assertSame('Check template_id, or ' . self::SEND_SINGLY, $error->getFix()); + $this->assertSame( + ['not_found', 'Template is archived.', 'template_id'], + [$error->getErrorCode(), $error->getMessage(), $error->getField()] + ); } public static function retriesAfterAnUnconfirmingAttempt(): array From 37dd76ac625982ab83bfedac60bc9337fa0036dd Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:12:41 +0100 Subject: [PATCH 42/44] fix(emails): don't say a retried batch sent nothing after a lost answer A 404 on a retry after a lost answer now says an earlier attempt may have queued the email, so the caller keeps the same-key advice. A code batch's 404 names sending from code too, and its fix applies only when the project can send email from code. Co-Authored-By: Claude Opus 5.5 --- lib/Internal/EmailBatch.php | 14 ++++++++------ test/EmailsBatchTest.php | 27 +++++++++++++++++++++++++-- 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index 7e02f49..88eea47 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -304,17 +304,19 @@ private function requestError(array $fields, int $status, array $headers): Email { $answered = array_filter($fields, static fn($value): bool => $value !== null); if ($status === 404 && self::namesNoField($answered)) { + $cause = $this->isTemplateForm + ? "PostHog found no template with this template_id, or batch sends aren't available for this " + . 'project, so it' + : "Batch sends or sending from code aren't available for this project, so PostHog"; $answered = [ ...array_diff_key($answered, ['why' => true]), 'code' => 'not_found', - 'detail' => $this->isTemplateForm - ? "PostHog found no template with this template_id, or batch sends aren't available for this " - . 'project, so it sent no email of this request.' - : "Batch sends from code aren't available for this project, so PostHog sent no email of this " - . 'request.', + 'detail' => $this->mayHaveQueued + ? "$cause refused this retry. An earlier attempt may have queued the email." + : "$cause sent no email of this request.", 'fix' => $this->isTemplateForm ? "Check template_id. If it's right, " . self::SEND_EACH_ON_ITS_OWN - : ucfirst(self::SEND_EACH_ON_ITS_OWN), + : 'If the project can send email from code, ' . self::SEND_EACH_ON_ITS_OWN, ]; } if ($status === 413) { diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index c049229..95c6c48 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -30,6 +30,8 @@ class EmailsBatchTest extends TestCase private const WARNING_LOGGED = '[PostHog][Emails] Email warning sandbox_sender: Sent from the test sender.'; private const SEND_SINGLY = "send each email the batch didn't queue with emails()->send() and its recipient's " . 'idempotency_key.'; + private const SEND_AGAIN = 'Send it again with the same idempotency_key within 24 hours of its first use, so it ' + . 'goes out once.'; private const SEND_EACH_ON_ITS_OWN = 'send each recipient on its own with emails()->send() and its ' . 'idempotency_key until batch sends are available.'; @@ -1189,14 +1191,35 @@ public function testA404WithoutAFieldOnACodeBatchSaysToSendEachRecipientOnItsOwn $this->assertSame(['not_found', 404], [$error->getErrorCode(), $error->getStatusCode()]); $this->assertSame( - "Batch sends from code aren't available for this project, so PostHog sent no email of this request.", + "Batch sends or sending from code aren't available for this project, so PostHog sent no email of this " + . 'request.', $error->getMessage() ); - $this->assertSame(ucfirst(self::SEND_EACH_ON_ITS_OWN), $error->getFix()); + $this->assertSame('If the project can send email from code, ' . self::SEND_EACH_ON_ITS_OWN, $error->getFix()); $this->assertNull($error->getWhy()); $this->assertSame(['failed'], self::statuses($error->getResults())); } + public function testA404OnARetryAfterALostAnswerDoesNotSayNothingWasSent(): void + { + $this->reply( + self::networkError(), + [404, '{"type":"invalid_request","code":"not_found","detail":"Not found."}', []] + ); + + $error = $this->batchError(self::recipients(2), ['max_retries' => 1]); + + $this->assertSame(['unconfirmed', 'unconfirmed'], self::statuses($error->getResults())); + foreach ([$error, ...array_map(static fn($r): EmailError => $r->getError(), $error->getResults())] as $read) { + $this->assertStringNotContainsString('sent no email', $read->getMessage()); + $this->assertStringContainsString('may have queued', $read->getMessage()); + } + $this->assertSame( + [self::SEND_AGAIN, self::SEND_AGAIN], + array_map(static fn($r): ?string => $r->getError()->getFix(), $error->getResults()) + ); + } + public function testA404ThatNamesAFieldKeepsPostHogsAnswer(): void { $this->reply([404, '{"type":"invalid_request","code":"not_found","detail":"Template is archived.",' From f661ea59aca0795d1150b8f83479f6135774f7bd Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:14:52 +0100 Subject: [PATCH 43/44] fix(emails): keep batch recipients unconfirmed on unclear 409s and refused retries Only a 409 batch_unavailable marks a batch's recipients failed; any other 409 leaves them unconfirmed with their keys. A refusal of a retry after a lost answer now says some emails may have gone out and tells the caller to send each recipient again with the same key. An unconfirmed recipient's message always says PostHog didn't confirm the email and it may still go out. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- lib/Emails.php | 9 ++- lib/Internal/EmailBatch.php | 61 +++++++++-------- test/EmailsBatchTest.php | 128 ++++++++++++++++++++++++++++++------ 4 files changed, 150 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index 9152c00..55f817b 100644 --- a/README.md +++ b/README.md @@ -108,8 +108,8 @@ foreach ($result->getResults() as $email) { - **Recipients.** Each recipient has `to` and optional `distinct_id`, `idempotency_key` and `template_data`. A recipient's `template_data` is merged over the shared `template_data`, and its keys replace the shared ones. With `template_key`, the content is the same for every recipient, so a recipient can't carry `template_data`. A batch takes no `cc`, `bcc`, `attachments` or `scheduled_at`: send those emails with `send()`. - **Requests.** A batch takes 1 to 100 recipients and goes out in one request. The client waits at least 45 seconds for the answer. More than 100 recipients throws `invalid_recipients` before any request. - **Idempotency keys.** Every retry reuses each recipient's key, so a retry never queues an email twice. Without a key, the client makes one that covers its own retries but not a second call. When a batch may be cut off and run again, pass keys you store: send it again with the same key within 24 hours of its first use, so it goes out once. Each recipient of a call needs a different key. Build each key from an ID you store with the job, such as the digest's own ID, never from the time of the run: a retry after midnight would make new keys and send the emails again. Never reuse a key for another email: PostHog sends one email per key, so the other doesn't go out. PostHog usually refuses it with `idempotency_key_reused`, but two sends that arrive at the same time can both answer `queued`. -- **Statuses.** `getStatus()` is `queued` when PostHog accepted the email, `failed` when it refused it (`getError()` says why, such as a suppressed address), and `unconfirmed` when the client can't tell, such as after a lost answer. Send each `unconfirmed` email again with the same key within 24 hours of its first use, so it goes out once. `getWarnings()` holds PostHog's warnings. -- **Errors.** When PostHog refuses the batch as a whole, such as a rate limit past its retries, `batch()` throws `PostHog\EmailBatchError`, whose `getResults()` holds every recipient. `getFix()` carries PostHog's advice. `content_too_large` with status 413 means the request is larger than PostHog takes: send fewer recipients in each batch, or a smaller email. With status 400 it means the content or `template_data` every recipient shares is too large, so fewer recipients won't help: make it smaller, or send those emails one at a time with `send()`. `batch_unavailable` (409) means the project can't send batches yet, and is never retried: send each email the batch didn't queue with `send()` and its recipient's `idempotency_key`. `not_found` (404) without a field means PostHog found no template with that `template_id`, or batch sends aren't available for the project. Check the `template_id`. If it's right, send each recipient on its own with `send()` and its `idempotency_key` until batch sends are available. +- **Statuses.** `getStatus()` is `queued` when PostHog accepted the email, `failed` when it refused it (`getError()` says why, such as a suppressed address), and `unconfirmed` when the client can't tell, such as after a lost answer or a 409 other than `batch_unavailable`. Send each `unconfirmed` email again with the same key within 24 hours of its first use, so it goes out once. `getWarnings()` holds PostHog's warnings. +- **Errors.** When PostHog refuses the batch as a whole, such as a rate limit past its retries, `batch()` throws `PostHog\EmailBatchError`, whose `getResults()` holds every recipient. `getFix()` carries PostHog's advice. `content_too_large` with status 413 means the request is larger than PostHog takes: send fewer recipients in each batch, or a smaller email. With status 400 it means the content or `template_data` every recipient shares is too large, so fewer recipients won't help: make it smaller, or send those emails one at a time with `send()`. `batch_unavailable` (409) means the project can't send batches yet, and is never retried: send each email the batch didn't queue with `send()` and its recipient's `idempotency_key`. `not_found` (404) without a field means PostHog found no template with that `template_id`, or batch sends aren't available for the project. Check the `template_id`. If it's right, send each recipient on its own with `send()` and its `idempotency_key` until batch sends are available. When an earlier attempt got no answer, a refusal of the retry doesn't prove nothing went out: the error says some emails may have gone out, every recipient stays `unconfirmed`, and `getFix()` says to send each one again with the same `idempotency_key`. ## Questions? diff --git a/lib/Emails.php b/lib/Emails.php index c82dd79..80b860b 100644 --- a/lib/Emails.php +++ b/lib/Emails.php @@ -431,9 +431,9 @@ public function get(string $messageId): EmailStatus * * - `queued`: PostHog accepted the email. * - `failed`: PostHog refused it, and getError() says why, such as a suppressed address. - * - `unconfirmed`: the client can't tell whether PostHog accepted it, such as after a lost answer, or when - * another request still holds its key. Send it again with the same key within 24 hours of its first use, so - * it goes out once. + * - `unconfirmed`: the client can't tell whether PostHog accepted it, such as after a lost answer, or a 409 + * other than `batch_unavailable`, as when another request still holds its key. Send it again with the same + * key within 24 hours of its first use, so it goes out once. * * When PostHog refuses the batch as a whole, such as a rate limit past its retries, batch() throws * EmailBatchError, whose getResults() holds every recipient: `failed`, or `unconfirmed` when an attempt may have @@ -446,6 +446,9 @@ public function get(string $messageId): EmailStatus * `not_found` (404) without a field means PostHog found no template with that `template_id`, or batch sends * aren't available for the project. Check the `template_id`. If it's right, send each recipient on its own with * send() and its `idempotency_key` until batch sends are available. + * When an earlier attempt got no answer, a refusal of the retry doesn't prove nothing went out: the error says + * some emails may have gone out, every recipient stays `unconfirmed`, and getFix() says to send each one again + * with the same `idempotency_key`. * * ```php * $result = $client->emails()->batch([ diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index 88eea47..e8389fb 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -20,7 +20,10 @@ final class EmailBatch private const UNCONFIRMED_CODES = ['idempotency_key_in_flight', 'delivery_unavailable', 'api_error']; private const SEND_AGAIN = 'Send it again with the same idempotency_key within 24 hours of its first use, so it goes out once.'; + private const RESEND_EACH = 'Send each recipient again with the same idempotency_key within 24 hours of its ' + . 'first use, so each email goes out once.'; private const IN_FLIGHT = 'idempotency_key_in_flight'; + private const BATCH_UNAVAILABLE = 'batch_unavailable'; private const JSON_FLAGS = JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE; private const JSON_DEPTH = 514; private const SEND_SINGLY = "send each email the batch didn't queue with emails()->send() and its recipient's " @@ -167,8 +170,8 @@ public function requestBody(): string public function lost(EmailError $error): EmailError { $this->mayHaveQueued = true; - $inFlight = $error->getStatusCode() === 409 && $error->getErrorCode() === self::IN_FLIGHT; - $cause = $inFlight ? self::sendAgain($error, $error->getFix() ?? self::SEND_AGAIN) : self::unconfirmed(null); + $fix = $error->getErrorCode() === self::IN_FLIGHT ? $error->getFix() ?? self::SEND_AGAIN : self::SEND_AGAIN; + $cause = $error->getStatusCode() === 409 ? self::unconfirmedBy($error, $fix) : self::unconfirmed(null); $this->setAll('unconfirmed', $cause); return $error; @@ -181,16 +184,14 @@ public function answer(int $status, string $body, array $headers): void { $fields = EmailReplies::fields($body); if ($status < 200 || $status >= 300) { - $code = EmailReplies::text($fields['code'] ?? null); - $inFlight = $status === 409 && ($code === null || $code === self::IN_FLIGHT); - if ($status >= 500 || $inFlight) { - $this->mayHaveQueued = true; - $this->setAll('unconfirmed', self::unconfirmed(null)); - throw $this->lost($this->requestError($fields, $status, $headers)); - } + $mayHaveQueuedThisOne = $status >= 500 + || ($status === 409 && EmailReplies::text($fields['code'] ?? null) !== self::BATCH_UNAVAILABLE); $error = $this->requestError($fields, $status, $headers); + if ($mayHaveQueuedThisOne) { + throw $this->lost($error); + } if ($this->mayHaveQueued) { - $this->setAll('unconfirmed', self::sendAgain($error, self::SEND_AGAIN)); + $this->setAll('unconfirmed', self::unconfirmedBy($error, self::SEND_AGAIN)); } throw $error; } @@ -228,7 +229,7 @@ private function settle(int $index, array $slot): void } $answer = self::slotError($error, $messageId); if ($this->mayHaveQueued || in_array($answer->getErrorCode(), self::UNCONFIRMED_CODES, true)) { - $this->set($index, 'unconfirmed', $messageId, error: self::sendAgain($answer, self::SEND_AGAIN)); + $this->set($index, 'unconfirmed', $messageId, error: self::unconfirmedBy($answer, self::SEND_AGAIN)); return; } $this->set($index, 'failed', $messageId, error: $answer); @@ -311,9 +312,7 @@ private function requestError(array $fields, int $status, array $headers): Email $answered = [ ...array_diff_key($answered, ['why' => true]), 'code' => 'not_found', - 'detail' => $this->mayHaveQueued - ? "$cause refused this retry. An earlier attempt may have queued the email." - : "$cause sent no email of this request.", + 'detail' => "$cause sent no email of this request.", 'fix' => $this->isTemplateForm ? "Check template_id. If it's right, " . self::SEND_EACH_ON_ITS_OWN : 'If the project can send email from code, ' . self::SEND_EACH_ON_ITS_OWN, @@ -323,9 +322,18 @@ private function requestError(array $fields, int $status, array $headers): Email $answered['fix'] = EmailReplies::text($answered['fix'] ?? null) ?? 'Make the email or its template_data smaller, or send fewer recipients in each batch.'; } - if (($answered['code'] ?? null) === 'batch_unavailable') { + if (($answered['code'] ?? null) === self::BATCH_UNAVAILABLE) { $answered['fix'] = 'Until batch sends are on for the project, ' . self::SEND_SINGLY; } + if ($this->mayHaveQueued) { + $code = EmailReplies::text($answered['code'] ?? null) ?? 'api_error'; + $answered = [ + ...array_diff_key($answered, ['why' => true]), + 'detail' => "PostHog refused a retry of this batch with $code. An earlier attempt got no answer, so " + . "some of its emails may have gone out: read each recipient's result.", + 'fix' => self::RESEND_EACH, + ]; + } return EmailReplies::error($answered, $status, $headers); } @@ -370,19 +378,20 @@ private static function unconfirmed(?string $messageId): EmailError ); } - private static function sendAgain(EmailError $error, string $fix): EmailError + private static function unconfirmedBy(EmailError $answer, string $fix): EmailError { + $code = $answer->getErrorCode(); + return new EmailError( - $error->getErrorCode(), - $error->getMessage(), - $error->getStatusCode(), - $error->getWhy(), - $fix, - $error->getDocsUrl(), - $error->getField(), - $error->getRetryAfterMs(), - $error, - $error->getMessageId() + $code, + "PostHog didn't confirm this email: $code, so it may still go out.", + $answer->getStatusCode(), + fix: $fix, + docsUrl: $answer->getDocsUrl(), + field: $answer->getField(), + retryAfterMs: $answer->getRetryAfterMs(), + previous: $answer, + messageId: $answer->getMessageId() ); } } diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index 95c6c48..7532ed1 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -32,6 +32,10 @@ class EmailsBatchTest extends TestCase . 'idempotency_key.'; private const SEND_AGAIN = 'Send it again with the same idempotency_key within 24 hours of its first use, so it ' . 'goes out once.'; + private const RESEND_EACH = 'Send each recipient again with the same idempotency_key within 24 hours of its ' + . 'first use, so each email goes out once.'; + private const NOT_SAID_OF_AN_UNCONFIRMED_EMAIL = '/sent no|didn.t send|not sent|not queued|didn.t queue|failed|' + . 'split|smaller|new key/i'; private const SEND_EACH_ON_ITS_OWN = 'send each recipient on its own with emails()->send() and its ' . 'idempotency_key until batch sends are available.'; @@ -141,6 +145,11 @@ private static function slow(int $seconds, Closure $answer): Closure }; } + private static function unconfirmedMessage(string $code): string + { + return "PostHog didn't confirm this email: $code, so it may still go out."; + } + private static function networkError(): EmailError { return new EmailError('network_error', 'The request to PostHog failed: Connection reset.'); @@ -755,8 +764,9 @@ public function testARecipientARetryRefusesAfterALostAnswerStaysUnconfirmedWithI [ 'recipient_suppressed', 'Send it again with the same idempotency_key within 24 hours of its first use, so it goes out once.', + self::unconfirmedMessage('recipient_suppressed'), ], - [$second->getError()->getErrorCode(), $second->getError()->getFix()] + [$second->getError()->getErrorCode(), $second->getError()->getFix(), $second->getError()->getMessage()] ); } @@ -795,10 +805,11 @@ public function testARecipientPostHogDidNotConfirmIsUnconfirmedWithTheAdviceToSe ]); $sendAgain = 'Send it again with the same idempotency_key within 24 hours of its first use, ' . 'so it goes out once.'; - $this->assertSame([...$error, $sendAgain], [ + $this->assertSame([...$error, $sendAgain, self::unconfirmedMessage($error[0])], [ $result->getError()->getErrorCode(), $result->getError()->getStatusCode(), $result->getError()->getFix(), + $result->getError()->getMessage(), ]); } @@ -806,6 +817,18 @@ public static function slotsWithoutAConfirmation(): array { return [ 'not confirmed by the pipeline' => [self::notConfirmed(), ['delivery_unavailable', 503]], + 'not confirmed, in words that say it was not queued' => [ + ['message_id' => 'm0', 'error' => [ + 'code' => 'delivery_unavailable', + 'detail' => 'The email was not queued and not sent.', + 'status' => 503, + ]], + ['delivery_unavailable', 503], + ], + 'not confirmed, without words' => [ + ['message_id' => 'm0', 'error' => ['code' => 'idempotency_key_in_flight', 'status' => 409]], + ['idempotency_key_in_flight', 409], + ], 'an unreadable result' => [['message_id' => 'm0', 'status' => 'pending'], ['api_error', null]], ]; } @@ -841,7 +864,7 @@ public function testAWholeRequestInFlightAnswerLeavesItsRecipientsUnconfirmed(): $this->assertSame( [ 'idempotency_key_in_flight', - 'Nope.', + self::unconfirmedMessage('idempotency_key_in_flight'), 'Send it again with the same idempotency_key within 24 hours of its first use, so it goes out once.', ], [$recipientError->getErrorCode(), $recipientError->getMessage(), $recipientError->getFix()] @@ -1200,24 +1223,74 @@ public function testA404WithoutAFieldOnACodeBatchSaysToSendEachRecipientOnItsOwn $this->assertSame(['failed'], self::statuses($error->getResults())); } - public function testA404OnARetryAfterALostAnswerDoesNotSayNothingWasSent(): void + public static function refusalsOfARetryAfterALostAnswer(): array { - $this->reply( - self::networkError(), - [404, '{"type":"invalid_request","code":"not_found","detail":"Not found."}', []] - ); + return [ + 'a 400' => [[400, json_encode([ + 'type' => 'validation_error', + 'code' => 'invalid_template_data', + 'detail' => 'template_data is invalid, so no email was sent.', + 'why' => 'Nothing of this request was sent.', + ]), []], 'invalid_template_data'], + 'a 404 without a field' => [ + [404, '{"type":"invalid_request","code":"not_found","detail":"Not found."}', []], + 'not_found', + ], + 'batch sends off' => [[409, json_encode([ + 'type' => 'invalid_request', + 'code' => 'batch_unavailable', + 'detail' => "Batch sends aren't on for this project, so PostHog sent no email.", + ]), []], 'batch_unavailable'], + 'a batch too large' => [[413, json_encode([ + 'type' => 'invalid_request', + '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.', + ]), []], 'content_too_large'], + 'a 413 without a body' => [[413, '', []], 'api_error'], + ]; + } + + #[DataProvider('refusalsOfARetryAfterALostAnswer')] + public function testARefusedRetryAfterALostAnswerSaysSomeEmailsMayHaveGoneOutAndToResendWithTheSameKeys( + array $refusal, + string $code + ): void { + $this->reply(self::networkError(), $refusal); $error = $this->batchError(self::recipients(2), ['max_retries' => 1]); - $this->assertSame(['unconfirmed', 'unconfirmed'], self::statuses($error->getResults())); - foreach ([$error, ...array_map(static fn($r): EmailError => $r->getError(), $error->getResults())] as $read) { - $this->assertStringNotContainsString('sent no email', $read->getMessage()); - $this->assertStringContainsString('may have queued', $read->getMessage()); - } + $this->assertCount(2, $this->requests); $this->assertSame( - [self::SEND_AGAIN, self::SEND_AGAIN], - array_map(static fn($r): ?string => $r->getError()->getFix(), $error->getResults()) + [ + $code, + $refusal[0], + "PostHog refused a retry of this batch with $code. An earlier attempt got no answer, so some of its " + . "emails may have gone out: read each recipient's result.", + self::RESEND_EACH, + null, + ], + [$error->getErrorCode(), $error->getStatusCode(), $error->getMessage(), $error->getFix(), $error->getWhy()] + ); + $this->assertSame( + [ + ['unconfirmed', 'key-0', $code, self::unconfirmedMessage($code), self::SEND_AGAIN], + ['unconfirmed', 'key-1', $code, self::unconfirmedMessage($code), self::SEND_AGAIN], + ], + array_map(static fn($r): array => [ + $r->getStatus(), + $r->getIdempotencyKey(), + $r->getError()->getErrorCode(), + $r->getError()->getMessage(), + $r->getError()->getFix(), + ], $error->getResults()) ); + foreach ([$error, ...array_map(static fn($r): EmailError => $r->getError(), $error->getResults())] as $read) { + $this->assertDoesNotMatchRegularExpression( + self::NOT_SAID_OF_AN_UNCONFIRMED_EMAIL, + $read->getMessage() . ' ' . $read->getFix() . ' ' . $read->getWhy() + ); + } } public function testA404ThatNamesAFieldKeepsPostHogsAnswer(): void @@ -1384,25 +1457,38 @@ public function testARetryWaitOnAWorkingClockNeedsNoHrtime(): void $this->assertSame([0, '["queued",2]'], self::runWithPhpOptions($script, '-d disable_functions=hrtime')); } - public static function unreadableInFlightAnswers(): array + public static function conflictsOtherThanBatchUnavailable(): array { return [ 'an empty body' => [''], 'a body that is not JSON' => ['Conflict'], + 'a generic code' => ['{"type":"server_error","code":"api_error","detail":"Conflict."}'], + 'a proxy conflict' => ['{"code":"conflict","detail":"The email failed: conflict."}'], ]; } - #[DataProvider('unreadableInFlightAnswers')] - public function testA409WithAnUnreadableBodyLeavesItsRecipientsUnconfirmedWithTheirKeys(string $body): void + #[DataProvider('conflictsOtherThanBatchUnavailable')] + public function testA409OtherThanBatchUnavailableLeavesItsRecipientsUnconfirmedWithTheirKeys(string $body): void { $this->reply([409, $body, []]); - $error = $this->batchError(self::recipients(2), ['max_retries' => 0]); + $error = $this->batchError(self::recipients(2), ['max_retries' => 2]); + $this->assertCount(1, $this->requests); $this->assertSame( - [['unconfirmed', 'key-0'], ['unconfirmed', 'key-1']], - array_map(static fn($r): array => [$r->getStatus(), $r->getIdempotencyKey()], $error->getResults()) + [['unconfirmed', 'key-0', self::SEND_AGAIN], ['unconfirmed', 'key-1', self::SEND_AGAIN]], + array_map( + static fn($r): array => [$r->getStatus(), $r->getIdempotencyKey(), $r->getError()->getFix()], + $error->getResults() + ) ); + foreach ($error->getResults() as $result) { + $this->assertStringContainsString("PostHog didn't confirm this email", $result->getError()->getMessage()); + $this->assertDoesNotMatchRegularExpression( + self::NOT_SAID_OF_AN_UNCONFIRMED_EMAIL, + $result->getError()->getMessage() + ); + } } public static function setupErrors(): array From f3ca54a22c83655c8451849e226e20703278e001 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:26:00 +0100 Subject: [PATCH 44/44] fix(emails): say an unclear 409 may have queued and keep PostHog's in-flight and 503 answers A batch 409 other than batch_unavailable or idempotency_key_in_flight now says some emails may have gone out and to send each recipient again with the same key, instead of passing the server's own advice through. The lost-answer rewrite now runs only on refusals, so a final in-flight answer or 503 keeps PostHog's text and fix. Co-Authored-By: Claude Opus 5.5 --- lib/Internal/EmailBatch.php | 16 ++++++++--- test/EmailsBatchTest.php | 54 ++++++++++++++++++++++++++++++++++++- 2 files changed, 65 insertions(+), 5 deletions(-) diff --git a/lib/Internal/EmailBatch.php b/lib/Internal/EmailBatch.php index e8389fb..fd90e15 100644 --- a/lib/Internal/EmailBatch.php +++ b/lib/Internal/EmailBatch.php @@ -325,12 +325,20 @@ private function requestError(array $fields, int $status, array $headers): Email if (($answered['code'] ?? null) === self::BATCH_UNAVAILABLE) { $answered['fix'] = 'Until batch sends are on for the project, ' . self::SEND_SINGLY; } - if ($this->mayHaveQueued) { - $code = EmailReplies::text($answered['code'] ?? null) ?? 'api_error'; + $code = EmailReplies::text($answered['code'] ?? null) ?? 'api_error'; + $detail = match (true) { + $status >= 500, $code === self::IN_FLIGHT && $status === 409 => null, + $status === 409 && $code !== self::BATCH_UNAVAILABLE => "PostHog answered the batch with a 409 ($code) " + . "that doesn't say whether it queued the emails, so some of them may have gone out: read each " + . "recipient's result.", + $this->mayHaveQueued => "PostHog refused a retry of this batch with $code. An earlier attempt got no " + . "answer, so some of its emails may have gone out: read each recipient's result.", + default => null, + }; + if ($detail !== null) { $answered = [ ...array_diff_key($answered, ['why' => true]), - 'detail' => "PostHog refused a retry of this batch with $code. An earlier attempt got no answer, so " - . "some of its emails may have gone out: read each recipient's result.", + 'detail' => $detail, 'fix' => self::RESEND_EACH, ]; } diff --git a/test/EmailsBatchTest.php b/test/EmailsBatchTest.php index 7532ed1..90b714e 100644 --- a/test/EmailsBatchTest.php +++ b/test/EmailsBatchTest.php @@ -1293,6 +1293,49 @@ public function testARefusedRetryAfterALostAnswerSaysSomeEmailsMayHaveGoneOutAnd } } + public function testAnInFlightAnswerAfterALostAnswerKeepsPostHogsAnswerAndFix(): void + { + $this->reply(self::networkError(), [409, json_encode([ + 'type' => 'invalid_request', + 'code' => 'idempotency_key_in_flight', + 'detail' => 'Another request with this key is in progress.', + 'fix' => 'Wait a minute, then send it again with the same idempotency_key.', + ]), []]); + + $error = $this->batchError(self::recipients(1), ['max_retries' => 1]); + + $this->assertSame( + [ + 'Another request with this key is in progress.', + 'Wait a minute, then send it again with the same idempotency_key.', + ], + [$error->getMessage(), $error->getFix()] + ); + [$result] = $error->getResults(); + $this->assertSame( + ['unconfirmed', 'Wait a minute, then send it again with the same idempotency_key.'], + [$result->getStatus(), $result->getError()->getFix()] + ); + } + + public function testA503AfterALostAnswerKeepsPostHogsAnswer(): void + { + $this->reply(self::networkError(), [503, json_encode([ + 'type' => 'server_error', + 'code' => 'delivery_unavailable', + 'detail' => 'Email delivery is down for maintenance.', + 'why' => 'A planned upgrade.', + ]), []]); + + $error = $this->batchError(self::recipients(1), ['max_retries' => 1]); + + $this->assertSame( + ['delivery_unavailable', 'Email delivery is down for maintenance.', 'A planned upgrade.'], + [$error->getErrorCode(), $error->getMessage(), $error->getWhy()] + ); + $this->assertSame(['unconfirmed'], self::statuses($error->getResults())); + } + public function testA404ThatNamesAFieldKeepsPostHogsAnswer(): void { $this->reply([404, '{"type":"invalid_request","code":"not_found","detail":"Template is archived.",' @@ -1463,7 +1506,9 @@ public static function conflictsOtherThanBatchUnavailable(): array 'an empty body' => [''], 'a body that is not JSON' => ['Conflict'], 'a generic code' => ['{"type":"server_error","code":"api_error","detail":"Conflict."}'], - 'a proxy conflict' => ['{"code":"conflict","detail":"The email failed: conflict."}'], + 'a proxy conflict' => [ + '{"code":"conflict","detail":"The email failed: conflict.","fix":"Send it again with a new key."}', + ], ]; } @@ -1475,6 +1520,13 @@ public function testA409OtherThanBatchUnavailableLeavesItsRecipientsUnconfirmedW $error = $this->batchError(self::recipients(2), ['max_retries' => 2]); $this->assertCount(1, $this->requests); + $this->assertSame(409, $error->getStatusCode()); + $this->assertStringContainsString('some of them may have gone out', $error->getMessage()); + $this->assertSame([self::RESEND_EACH, null], [$error->getFix(), $error->getWhy()]); + $this->assertDoesNotMatchRegularExpression( + self::NOT_SAID_OF_AN_UNCONFIRMED_EMAIL, + $error->getMessage() . ' ' . $error->getFix() + ); $this->assertSame( [['unconfirmed', 'key-0', self::SEND_AGAIN], ['unconfirmed', 'key-1', self::SEND_AGAIN]], array_map(