diff --git a/.changeset/email-batch-sends.md b/.changeset/email-batch-sends.md new file mode 100644 index 0000000..e1ff874 --- /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. 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 cf510a5..f4be3e7 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,33 @@ $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 +// $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' => "$digestId:ada"], + ['to' => 'alan@example.com', 'template_data' => ['name' => 'Alan'], 'idempotency_key' => "$digestId: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.** 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 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? ### [Join our Slack community.](https://join.slack.com/t/posthogusers/shared_invite/enQtOTY0MzU5NjAwMDY3LTc2MWQ0OTZlNjhkODk3ZDI3NDVjMDE1YjgxY2I4ZjI4MzJhZmVmNjJkN2NmMGJmMzc2N2U3Yjc3ZjI5NGFlZDQ) diff --git a/api/public-api.json b/api/public-api.json index 8fc5a61..b51923a 100644 --- a/api/public-api.json +++ b/api/public-api.json @@ -2,6 +2,145 @@ "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 + } + ] + }, + "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": [] + }, + "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 +1834,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, @@ -2191,6 +2397,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, @@ -5533,6 +5757,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..28a2d99 --- /dev/null +++ b/lib/BatchEmailResult.php @@ -0,0 +1,93 @@ +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` or `unconfirmed`. + */ + public function getStatus(): string + { + return $this->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 + { + 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. 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 + { + return $this->error; + } +} diff --git a/lib/EmailBatchError.php b/lib/EmailBatchError.php new file mode 100644 index 0000000..b8c8d8c --- /dev/null +++ b/lib/EmailBatchError.php @@ -0,0 +1,53 @@ + $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 batch. + * + * @return list + */ + public function getWarnings(): array + { + return $this->warnings; + } +} diff --git a/lib/EmailError.php b/lib/EmailError.php index 1f2c97f..3ea2f08 100644 --- a/lib/EmailError.php +++ b/lib/EmailError.php @@ -173,17 +173,20 @@ 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', + str_starts_with($code, 'invalid_') => 'validation_error', + default => 'application_error', + }; } return match ($status) { 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/lib/Emails.php b/lib/Emails.php index 46a9d9f..d214821 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 PostHog\Internal\ScheduledEmailResult; use Symfony\Component\Clock\Clock; use Symfony\Component\Clock\ClockInterface; @@ -17,7 +20,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 @@ -48,6 +51,7 @@ 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 US_APP_HOST = 'https://us.posthog.com'; private const EU_APP_HOST = 'https://eu.posthog.com'; private const CLOUD_APP_HOSTS = [ @@ -58,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'; @@ -384,6 +397,123 @@ 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 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 + * 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 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`. + * + * 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, 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 + * 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 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`. + * + * ```php + * $result = $client->emails()->batch([ + * 'template_id' => '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b', + * 'recipients' => [ + * ['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) { + * 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 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. + */ + public function batch(array $batch): SendBatchResult + { + [$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); + } 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. @@ -391,14 +521,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] = EmailRecipient::address($email); $hasTemplateId = array_key_exists('template_id', $email); if ($hasTemplateId === array_key_exists('template_key', $email)) { throw new EmailError( @@ -407,21 +530,8 @@ 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'); - } + $idempotencyKey = EmailRecipient::idempotencyKey($email); + $maxRetries = $this->maxRetries($email); $scheduledAt = array_key_exists('scheduled_at', $email) ? self::scheduledAt($email['scheduled_at']) : null; $payload['to'] = $to; if ($distinctId !== null) { @@ -443,6 +553,47 @@ private function prepareSend(array $email): array return [$body, $idempotencyKey ?? Uuid::v4(), $maxRetries, $files, $scheduledAt]; } + /** + * @return array{array, int} The email every recipient gets, 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, $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) { @@ -503,7 +654,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) { @@ -517,7 +668,7 @@ private static function templateContent(array $email): array 'template_data' ); } - self::refuseFieldsOutside($email, true); + self::refuseFieldsOutside($email, true, $call); return [ 'template_id' => strtolower($templateId), @@ -528,7 +679,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) { @@ -538,10 +689,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) { @@ -556,7 +707,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' ); } @@ -768,7 +919,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; @@ -778,7 +929,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."); } @@ -885,7 +1036,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) ); } @@ -901,15 +1052,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) { @@ -992,6 +1143,36 @@ 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 the batch." + ); + $url = $appHost . self::BATCH_PATH; + $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) { + throw in_array($error->getErrorCode(), self::LOST_ANSWER_CODES, true) ? $run->lost($error) : $error; + } + $run->answer(...$reply); + }, $closedBeforeARetry); + } catch (EmailError $error) { + throw $run->failure($error); + } catch (Throwable $throwable) { + throw $run->interrupted(new EmailError( + 'client_error', + 'The client failed while sending the batch: ' . $throwable->getMessage(), + previous: $throwable + )); + } + } + /** * @return array{string, string} */ @@ -1077,9 +1258,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 { @@ -1089,7 +1272,7 @@ private function withRetries(int $maxRetries, Closure $attemptOnce): mixed if ($delayMs === null) { throw $error; } - $this->waitToRetry($delayMs, $error); + $this->waitToRetry($delayMs, $closedBeforeARetry ?? $error); } } } @@ -1097,23 +1280,46 @@ private function withRetries(int $maxRetries, Closure $attemptOnce): mixed private function waitToRetry(int $delayMs, EmailError $error): void { $clock = self::forwardOnlyClock(); - $start = $clock->now(); + $started = $clock === null ? hrtime() : null; + $start = $clock?->now(); while (!($this->isClosed)()) { - $remainingUs = $delayMs * 1000 - self::microsecondsBetween($start, $clock->now()); + $elapsedUs = $clock === null + ? self::microsecondsSince($started) + : 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 { - $clock = Clock::get(); + 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; + /** + * @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 @@ -1128,11 +1334,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\\"); @@ -1175,9 +1376,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); } /** @@ -1253,25 +1456,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 || ($mayGoNow && self::sendsNow($fields))) { return new SendEmailResult($id, $replayed, $warnings); @@ -1343,56 +1536,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) - ); - } - - /** - * @return array - */ - private static function replyFields(string $body): array - { - $payload = json_decode($body, true); - return is_array($payload) && !array_is_list($payload) ? $payload : []; - } + $reason = EmailReplies::text($fields['reason'] ?? null); - 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; } @@ -1403,43 +1566,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..fd90e15 --- /dev/null +++ b/lib/Internal/EmailBatch.php @@ -0,0 +1,405 @@ +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 = []; + /** @var list */ + private array $warnings = []; + /** @var array>> */ + private array $warningKeys = []; + private bool $mayHaveQueued = false; + + /** + * @param list $members + */ + private function __construct(private array $members, private string $body, private bool $isTemplateForm) + { + } + + /** + * @param array $shared The email every recipient gets, as the request carries it. + */ + public static function prepare(array $shared, mixed $recipients): 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' + ); + } + 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 = []; + $wires = []; + $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[] = ['to' => $member['to'], 'key' => $member['key']]; + $wires[] = $member['wire']; + } + $request = [...$shared, 'recipients' => $wires]; + try { + return new self( + $members, + json_encode($request, self::JSON_FLAGS, self::JSON_DEPTH), + $isTemplateForm + ); + } catch (JsonException $exception) { + throw new EmailError( + 'invalid_form', + 'The email could not be encoded as JSON, so no email was sent: ' . $exception->getMessage() . '.', + previous: $exception + ); + } + } + + /** + * @return array{to: string, key: string, wire: array} + */ + 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] = EmailRecipient::address($recipient, $index); + $wire = ['to' => $to, 'idempotency_key' => EmailRecipient::idempotencyKey($recipient, $index) ?? 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' => $wire]; + } + + 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; + } + + + public function requestBody(): string + { + return $this->body; + } + + public function lost(EmailError $error): EmailError + { + $this->mayHaveQueued = true; + $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; + } + + /** + * @param list $headers + */ + public function answer(int $status, string $body, array $headers): void + { + $fields = EmailReplies::fields($body); + if ($status < 200 || $status >= 300) { + $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::unconfirmedBy($error, self::SEND_AGAIN)); + } + throw $error; + } + $slots = $fields['results'] ?? null; + 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 + )); + } + foreach (array_keys($this->members) as $index) { + $this->settle($index, is_array($slots[$index]) ? $slots[$index] : []); + } + foreach (EmailReplies::warnings($fields) as $warning) { + $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; + } + } + } + + /** + * @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 ($this->mayHaveQueued || in_array($answer->getErrorCode(), self::UNCONFIRMED_CODES, true)) { + $this->set($index, 'unconfirmed', $messageId, error: self::unconfirmedBy($answer, self::SEND_AGAIN)); + return; + } + $this->set($index, 'failed', $messageId, error: $answer); + } + + 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) { + $this->setAll('failed', $error); + } + + return new EmailBatchError($error, $this->outcome(), $this->warnings); + } + + private function setAll(string $status, EmailError $error): void + { + foreach (array_keys($this->members) as $index) { + $this->set($index, $status, error: $error); + } + } + + /** + * @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 + ): void { + $member = $this->members[$index]; + $this->results[$index] = new BatchEmailResult( + $index, + $member['to'], + $member['key'], + $status, + $messageId, + $replayed, + $error + ); + } + + /** + * @param array $fields + * @param list $headers + */ + private function requestError(array $fields, int $status, array $headers): EmailError + { + $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' => "$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, + ]; + } + if ($status === 413) { + $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) === self::BATCH_UNAVAILABLE) { + $answered['fix'] = 'Until batch sends are on for the project, ' . self::SEND_SINGLY; + } + $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' => $detail, + 'fix' => self::RESEND_EACH, + ]; + } + + 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)) { + 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. " . self::SEND_AGAIN, + messageId: $messageId + ); + } + + private static function unconfirmedBy(EmailError $answer, string $fix): EmailError + { + $code = $answer->getErrorCode(); + + return new EmailError( + $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/lib/Internal/EmailRecipient.php b/lib/Internal/EmailRecipient.php new file mode 100644 index 0000000..94d6874 --- /dev/null +++ b/lib/Internal/EmailRecipient.php @@ -0,0 +1,64 @@ + $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} The address and the distinct ID. + */ + public static function address(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); + } + + 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 + && (!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 $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..9f9f901 --- /dev/null +++ b/lib/Internal/EmailReplies.php @@ -0,0 +1,111 @@ + 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..5a0d349 --- /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. + * + * @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..90b714e --- /dev/null +++ b/test/EmailsBatchTest.php @@ -0,0 +1,1568 @@ +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 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.'; + + 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 */ + 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 + { + 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 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.'); + } + + /** @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 */ + private function requestUrls(): array + { + return array_column($this->requests, 'url'); + } + + /** @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->assertSame([], $result->getWarnings()); + } + + public function testATemplateBatchWithoutDataSendsAnEmptyObject(): void + { + $this->reply(self::allQueued()); + + $this->batch([['to' => 'a@example.com', 'idempotency_key' => 'k', 'template_data' => []]]); + + $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 + { + $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 testMoreThan100RecipientsAreRefusedBeforeAnyRequest(): void + { + $error = $this->refusal(['recipients' => self::recipients(101), 'template_id' => self::TEMPLATE_ID]); + + $this->assertNotInstanceOf(EmailBatchError::class, $error); + $this->assertSame( + ['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); + } + + #[DataProvider('tooLargeAnswers')] + 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]); + + $this->assertSame(['content_too_large', $status, 'Nope.', $fix], [ + $error->getErrorCode(), + $error->getStatusCode(), + $error->getMessage(), + $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], + '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.', + ], + ]; + } + + public function testAHundredRecipientsGoOutInOneRequest(): void + { + $this->reply(self::allQueued()); + + $result = $this->batch(self::recipients(100)); + + $this->assertSame([100], $this->recipientsPerRequest()); + $this->assertSame(self::times(100, 'queued'), self::statuses($result->getResults())); + } + + public function testARecipientIsEncodedWithoutExtraCopiesOfItsData(): void + { + $script = <<<'PHP' + [ + 200, + '{"results":[{"message_id":"m0","error":{"code":"content_too_large","detail":"Too large.","status":400}}]}', + [], +]); +$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(), ' ', $result->getResults()[0]->getError()->getErrorCode(); +PHP; + + $this->assertSame([0, 'failed content_too_large'], self::runWithPhpOptions($script, '-d memory_limit=32M')); + } + + #[DataProvider('recipientsNearTheBodyLimit')] + public function testAHundredRecipientsNearTheBodyLimitGoOutInTightMemory(int $each, int $last): void + { + $bodyFile = tempnam(sys_get_temp_dir(), 'posthog-emails-batch-body-'); + $script = "" . <<<'PHP' + array_map( + static fn(int $index): array => ['message_id' => "msg-$index", 'status' => 'queued'], + range(0, 99) + )]), []]; +}); +$recipients = []; +for ($index = 0; $index < 100; $index++) { + $size = $index === 99 ? $last : $each; + $recipients[] = ['to' => "user$index@example.com", 'template_data' => ['note' => str_repeat('x', $size)]]; +} +$result = $emails->batch([ + 'recipients' => $recipients, + 'template_id' => '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b', +]); +$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; + + try { + $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); + } + $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 recipient near the per-email limit' => [32000, 1400000], + ]; + } + + 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::runWithPhpOptions($script, '-d memory_limit=32M')); + } + + #[DataProvider('laterSerializations')] + public function testAValueThatFailsToEncodeOnceIsRefusedWithoutARequestWhateverItDoesLater(Closure $later): void + { + $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 : ($this->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 static function laterSerializations(): array + { + return [ + 'encodes later' => [static fn(): string => 'later'], + '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.'); + }], + ]; + } + + 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 + { + $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::runWithPhpOptions($script, '-d memory_limit=128M') + ); + } + + /** + * @return array{int, string} + */ + 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) . " $options " . escapeshellarg($script) . ' ' + . escapeshellarg(__DIR__ . '/../vendor/autoload.php') . ' 2>&1'; + exec($command, $output, $exitCode); + + return [$exitCode, implode("\n", $output)]; + } finally { + unlink($script); + } + } + + 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 testARecipientARetryRefusesAfterALostAnswerStaysUnconfirmedWithItsKey(): void + { + $this->reply( + self::networkError(), + self::ok(self::queued('m0', true), self::refused('m1', 'recipient_suppressed')) + ); + $recipients = self::recipients(2); + unset($recipients[1]['idempotency_key']); + + $result = $this->batch($recipients); + + $this->assertCount(2, $this->requests); + $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( + [ + '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()->getMessage()] + ); + } + + public function testA503ThenARefusalOfTheWholeRequestKeepsTheRecipientUnconfirmed(): void + { + $this->reply(self::wholeCall(503, 'delivery_unavailable'), self::wholeCall(422, 'sending_paused')); + + $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( + [ + 'sending_paused', + 422, + '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()] + ); + } + + #[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', 'key-0'], [ + $result->getStatus(), + $result->getMessageId(), + $result->getIdempotencyKey(), + ]); + $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, self::unconfirmedMessage($error[0])], [ + $result->getError()->getErrorCode(), + $result->getError()->getStatusCode(), + $result->getError()->getFix(), + $result->getError()->getMessage(), + ]); + } + + 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]], + ]; + } + + public function testABatchThatSucceedsReadsNothingBackForAnUnconfirmedEmail(): void + { + $this->reply(self::ok(self::queued('m0'), self::notConfirmed(null), self::notConfirmed('m2'))); + + $result = $this->batch(self::recipients(3), ['max_retries' => 0]); + + $this->assertSame([self::BATCH_URL], $this->requestUrls()); + $this->assertSame( + [['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')); + + $error = $this->batchError(self::recipients(2), ['max_retries' => 0]); + + $this->assertSame('idempotency_key_in_flight', $error->getErrorCode()); + $this->assertSame( + [['unconfirmed', null], ['unconfirmed', null]], + array_map(static fn($r): array => [$r->getStatus(), $r->getMessageId()], $error->getResults()) + ); + $recipientError = $error->getResults()[0]->getError(); + $this->assertSame( + [ + 'idempotency_key_in_flight', + 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()] + ); + $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 [ + '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('attemptsAfterAnInFlightAnswer')] + public function testAnAttemptThatMayHaveQueuedKeepsItsRecipientsUnconfirmedWhateverTheNextAnswers( + array $answers, + string $code + ): void { + $this->reply(...$answers); + + $error = $this->batchError(self::recipients(1), ['max_retries' => 1]); + + $this->assertSame($code, $error->getErrorCode()); + $this->assertSame(['unconfirmed'], self::statuses($error->getResults())); + $this->assertSame([self::BATCH_URL, self::BATCH_URL], $this->requestUrls()); + } + + public function testAShutdownDuringARetryWaitSendsNoRetry(): void + { + Clock::set(self::clockThatShutsDownOnSleep($this->clock, function (): void { + $this->closed = true; + })); + $this->reply(self::wholeCall(429), self::allQueued()); + + $error = $this->batchError(self::recipients(2), emails: $this->closedEmails()); + + $this->assertSame('client_closed', $error->getErrorCode()); + $this->assertCount(1, $this->requests); + $this->assertSame(['failed', 'failed'], self::statuses($error->getResults())); + $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()) + ); + } + + 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->assertSame('client_error', $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()) + ); + $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 [ + '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 { + 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 testARequestRefusedAsAWholeThrowsWithEveryRecipient(): void + { + $this->reply(self::wholeCall(429, 'quota_limited')); + + $error = $this->batchError(self::recipients(3)); + + $this->assertSame( + ['quota_limited', 429, 'Nope.'], + [$error->getErrorCode(), $error->getStatusCode(), $error->getMessage()] + ); + $this->assertCount(1, $this->requests); + $results = $error->getResults(); + $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 testARefusalOfTheWholeRequestAfterALostAnswerKeepsItsRecipientsUnconfirmedWithTheRefusal(): void + { + $this->reply(self::networkError(), self::wholeCall(429, 'quota_limited')); + + $error = $this->batchError(self::recipients(1)); + + [$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 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()); + } + + public function testALostAnswerAfterTheRetriesTellsEachRecipientToSendAgainWithItsKey(): void + { + $this->reply(self::networkError(), self::networkError(), self::networkError()); + + $error = $this->batchError(self::recipients(2)); + + $this->assertSame('network_error', $error->getErrorCode()); + $this->assertSame([self::BATCH_URL, self::BATCH_URL, self::BATCH_URL], $this->requestUrls()); + $this->assertSame( + [['unconfirmed', null, 'key-0'], ['unconfirmed', null, 'key-1']], + array_map( + static fn($r): array => [$r->getStatus(), $r->getMessageId(), $r->getIdempotencyKey()], + $error->getResults() + ) + ); + $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 of its first use, so it goes out once.', + $error->getResults()[1]->getError()->getMessage() + ); + } + + 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')); + + $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')); + + $error = $this->batchError(self::recipients(2), ['max_retries' => 2]); + + $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())); + } + + public static function notFoundAnswersWithoutAField(): array + { + return [ + '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('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 or sending from code aren't available for this project, so PostHog sent no email of this " + . 'request.', + $error->getMessage() + ); + $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 static function refusalsOfARetryAfterALostAnswer(): array + { + 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->assertCount(2, $this->requests); + $this->assertSame( + [ + $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 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.",' + . '"attr":"template_id"}', []]); + + $error = $this->batchError(self::recipients(1)); + + $this->assertSame( + ['not_found', 'Template is archived.', 'template_id'], + [$error->getErrorCode(), $error->getMessage(), $error->getField()] + ); + } + + 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 testARetryThatCannotConfirmEitherLeavesTheRecipientUnconfirmed( + mixed $first, + mixed $retry, + 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()); + } + + public function testAnAnswerWithoutAResultPerRecipientLeavesTheRequestUnconfirmed(): void + { + $this->reply(self::ok(self::queued('m0'))); + + $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([self::BATCH_URL], $this->requestUrls()); + } + + public function testWarningsReachTheCallerOnce(): void + { + global $errorMessages; + $warning = ['code' => 'sandbox_sender', 'detail' => 'Sent from the test sender.']; + $this->reply(self::allQueued(['warnings' => [$warning, $warning]])); + + $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 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 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 function testATransportThatThrowsKeepsTheRecipientsUnconfirmedWithTheirKeys(): void + { + $this->reply(static function (): never { + throw new Error('Call to undefined function curl_getinfo()'); + }); + + $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())); + $this->assertStringContainsString( + '"message_data":{"deep":' . json_encode($data) . '}', + (string) $this->requests[0]['body'] + ); + } + + 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 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.","fix":"Send it again with a new key."}', + ], + ]; + } + + #[DataProvider('conflictsOtherThanBatchUnavailable')] + public function testA409OtherThanBatchUnavailableLeavesItsRecipientsUnconfirmedWithTheirKeys(string $body): void + { + $this->reply([409, $body, []]); + + $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( + 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 + { + 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); + } +} 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(); diff --git a/test/EmailsOnOlderSymfonyClocksTest.php b/test/EmailsOnOlderSymfonyClocksTest.php index e5f4f9e..909b49d 100644 --- a/test/EmailsOnOlderSymfonyClocksTest.php +++ b/test/EmailsOnOlderSymfonyClocksTest.php @@ -20,23 +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 { - 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, $monotonicFails); $messageId = '01a18356-c56c-0001-e494-7666bc915188'; $emails = new Emails('phs_secret', 'us.i.posthog.com', transport: static fn(): array => [ 202, @@ -53,4 +44,51 @@ public function testAPastTimeQueuedNowIsAnAcceptance(bool $withoutTheClockClass) $this->assertSame($messageId, $result->getId()); $this->assertSame('queued', $result->getStatus()); } + + #[DataProvider('olderClocks')] + public function testABatchRetriesAfterALostAnswer(bool $withoutTheClockClass, bool $monotonicFails = false): void + { + self::loadWithAnOlderClock($withoutTheClockClass, $monotonicFails); + $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, bool $monotonicFails): void + { + foreach (spl_autoload_functions() as $loader) { + spl_autoload_unregister($loader); + $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 (!$without || $class !== 'Symfony\Component\Clock\Clock') { + $loader($class); + } + }); + } + } } diff --git a/test/EmailsTest.php b/test/EmailsTest.php index 7f8c50f..399ef39 100644 --- a/test/EmailsTest.php +++ b/test/EmailsTest.php @@ -19,19 +19,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 */ @@ -40,42 +35,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} @@ -154,18 +113,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 { @@ -217,33 +164,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 { @@ -1080,6 +1000,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], @@ -2412,6 +2342,17 @@ public function testAnErrorSerializedByTheVersionBeforeSchedulingStillReads(): v $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 testAQueuedResultSerializesAsTheVersionBeforeSchedulingDid(): void { $this->reply([202, '{"message_id":"msg_1"}', []]); 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); + } +}