diff --git a/.changeset/fruity-frogs-relax.md b/.changeset/fruity-frogs-relax.md new file mode 100644 index 00000000..afc116b8 --- /dev/null +++ b/.changeset/fruity-frogs-relax.md @@ -0,0 +1,5 @@ +--- +"posthog-laravel": minor +--- + +Send Mailables and mail notifications through PostHog: add a mailer with `'transport' => 'posthog'` in `config/mail.php` and set `MAIL_MAILER=posthog`. Each mail sends under its Mailable or notification class in kebab case as its template key, also through failover, round-robin and on-demand mailers; `X-PostHog-*` headers set the template key, distinct ID and idempotency key. Templates made in PostHog are not supported. diff --git a/packages/laravel/README.md b/packages/laravel/README.md index 4fb0cca6..7382a64c 100644 --- a/packages/laravel/README.md +++ b/packages/laravel/README.md @@ -304,6 +304,45 @@ No cache is enabled implicitly, and there is no background timer. The PHP client `loadFlags()` remains available for an explicit refresh. You can instead supply a custom provider class in `sdk.flag_definition_cache_provider`. +## Send email + +Add a `posthog` mailer to `config/mail.php` and set `MAIL_MAILER=posthog`. Every +Mailable and mail notification then sends through PostHog's transactional email +API. It needs `POSTHOG_API_KEY` and the project secret key in `POSTHOG_SECRET_KEY`: + +```php +'mailers' => [ + 'posthog' => [ + 'transport' => 'posthog', + // Optional: the template key of mail that has no class, such as Mail::raw(): + // 1 to 256 letters, digits, - and _. + 'default_template_key' => 'app-mail', + ], +], +``` + +Each mail sends under its class name in kebab case as its template key, so +`App\Mail\OrderShipped` groups as `order-shipped` in PostHog. Set options on a +Mailable with headers, which never go out with the email: + +```php +public function headers(): Headers +{ + return new Headers(text: [ + 'X-PostHog-Distinct-Id' => (string) $this->order->user_id, + // A queued Mailable retries with the same key, so PostHog sends it once. + 'X-PostHog-Idempotency-Key' => "order-{$this->order->id}-shipped", + ]); +} +``` + +`X-PostHog-Template-Key` overrides the template key. An email PostHog can't carry, +such as one with two `To` addresses or custom headers, throws +`PostHog cannot send this email: ` and sends nothing. A failed send throws +`PostHog\Mailer\PostHogTransportException`, whose `isRetryable()` says whether +sending again with the same idempotency key is safe. Templates made in PostHog +aren't supported here; send them with `PostHog::client()->emails()->send()`. + ## Laravel Pennant An optional read-only PostHog store supports Pennant boolean and variant reads. diff --git a/packages/laravel/src/Mail/MailDriver.php b/packages/laravel/src/Mail/MailDriver.php new file mode 100644 index 00000000..b16975e7 --- /dev/null +++ b/packages/laravel/src/Mail/MailDriver.php @@ -0,0 +1,127 @@ + 'posthog'` through PostHog's transactional email API, also inside a failover, round-robin + * or on-demand mailer. + * + * Each mail sends under its Mailable or notification class in kebab case as its template key, so + * `App\Mail\OrderShipped` sends as `order-shipped`. An `X-PostHog-Template-Key` header on the mail wins; + * mail with no class, such as `Mail::raw()`, uses the mailer's `default_template_key`, or `laravel`. + * Once PostHog has tried a mail, its `X-PostHog-*` headers are gone, so the next mailer of a failover + * never sends them. + */ +final class MailDriver implements TransportInterface +{ + private const INTEGRATION = 'laravel'; + private const TEMPLATE_KEY_LENGTH = 256; + private const NOT_IN_A_TEMPLATE_KEY = '/[^a-zA-Z0-9_-]+/'; + private const POSTHOG_HEADER = 'x-posthog-'; + + /** @var WeakMap|null The class-name key of each mail Laravel sends. */ + private static ?WeakMap $templateKeys = null; + + private function __construct(private readonly ?string $defaultTemplateKey) + { + if ($defaultTemplateKey !== null && preg_match(EmailMapper::TEMPLATE_KEY_PATTERN, $defaultTemplateKey) !== 1) { + throw new InvalidArgumentException( + 'The default template key can only have letters, digits, hyphens (-) and underscores (_), at most ' + . self::TEMPLATE_KEY_LENGTH . '.' + ); + } + } + + public static function extend(MailManager $manager): void + { + $manager->extend( + 'posthog', + static fn(array $config): self => new self($config['default_template_key'] ?? null) + ); + } + + /** + * Remembers the mail's class as its template key for the PostHog transport, without a header on the mail. + */ + public static function nameTheMail(MessageSending $event): void + { + $class = $event->data['__laravel_mailable'] ?? $event->data['__laravel_notification'] ?? null; + if (!is_string($class)) { + return; + } + $key = (string) preg_replace(self::NOT_IN_A_TEMPLATE_KEY, '-', Str::kebab(class_basename($class))); + $key = substr(trim($key, '-'), 0, self::TEMPLATE_KEY_LENGTH); + if ($key !== '') { + self::$templateKeys ??= new WeakMap(); + self::$templateKeys[$event->message] = $key; + } + } + + public function send(RawMessage $message, ?Envelope $envelope = null): ?SentMessage + { + $mail = $this->mailLaravelHandedOver($envelope) ?? $message; + try { + return $this->transportForThisSend(self::$templateKeys[$mail] ?? $this->defaultTemplateKey) + ->send($message, $envelope); + } finally { + self::removePostHogHeaders($mail); + } + } + + private static function removePostHogHeaders(RawMessage $mail): void + { + if (!$mail instanceof Message) { + return; + } + foreach ($mail->getHeaders()->getNames() as $name) { + if (str_starts_with($name, self::POSTHOG_HEADER)) { + $mail->getHeaders()->remove($name); + } + } + } + + /** + * A failover or round-robin mailer hands each transport a clone of the mail with Laravel's own envelope, + * which holds the mail Laravel named. + */ + private function mailLaravelHandedOver(?Envelope $envelope): ?RawMessage + { + if (!$envelope instanceof DelayedEnvelope) { + return null; + } + + return (fn(): ?RawMessage => $this->message ?? null)->call($envelope); + } + + private function transportForThisSend(?string $templateKey): PostHogTransport + { + return new PostHogTransport( + Container::getInstance()->make(PostHog::class)->client()->emails(), + integration: self::INTEGRATION . '/' . PostHog::VERSION, + defaultTemplateKey: $templateKey, + templates: false, + ); + } + + public function __toString(): string + { + return 'posthog'; + } +} diff --git a/packages/laravel/src/PostHogServiceProvider.php b/packages/laravel/src/PostHogServiceProvider.php index ff1a6eab..0aea6efc 100644 --- a/packages/laravel/src/PostHogServiceProvider.php +++ b/packages/laravel/src/PostHogServiceProvider.php @@ -10,6 +10,9 @@ use Illuminate\Queue\Events\JobProcessed; use Illuminate\Queue\Events\JobExceptionOccurred; use Illuminate\Queue\Events\Looping; +use Illuminate\Mail\Events\MessageSending; +use Illuminate\Mail\MailManager; +use PostHog\Laravel\Mail\MailDriver; use PostHog\Laravel\Middleware\RequestContext as RequestContextMiddleware; use PostHog\Laravel\Jobs\DeliverEvents; use Illuminate\Support\ServiceProvider; @@ -92,6 +95,9 @@ public function boot(): void $reporter->remember($event->exception, 'task', 'laravel.queue_job'); } }); + // Only an app that builds a mailer loads Laravel's mailer, Symfony Mailer and the PostHog transport. + $this->callAfterResolving('mail.manager', fn (MailManager $manager) => MailDriver::extend($manager)); + $events->listen(MessageSending::class, fn (MessageSending $event) => MailDriver::nameTheMail($event)); $events->listen(CommandStarting::class, function () { // The first CLI kernel may already be handling input when package providers boot. Container::getInstance()->make(ConsoleLifecycle::class)->startRoot(); diff --git a/packages/laravel/tests/Fixtures/InvoicePaid.php b/packages/laravel/tests/Fixtures/InvoicePaid.php new file mode 100644 index 00000000..f93596a7 --- /dev/null +++ b/packages/laravel/tests/Fixtures/InvoicePaid.php @@ -0,0 +1,19 @@ +from('billing@example.com')->subject('Invoice paid')->line('Thanks!'); + } +} diff --git a/packages/laravel/tests/Fixtures/OrderShipped.php b/packages/laravel/tests/Fixtures/OrderShipped.php new file mode 100644 index 00000000..0608864d --- /dev/null +++ b/packages/laravel/tests/Fixtures/OrderShipped.php @@ -0,0 +1,33 @@ + $headers + */ + public function __construct(private readonly array $headers = []) + { + } + + public function envelope(): Envelope + { + return new Envelope(from: 'shop@example.com', subject: 'Your order shipped'); + } + + public function content(): Content + { + return new Content(htmlString: '

On its way.

'); + } + + public function headers(): Headers + { + return new Headers(text: $this->headers); + } +} diff --git a/packages/laravel/tests/Fixtures/ShipmentUpdate.php b/packages/laravel/tests/Fixtures/ShipmentUpdate.php new file mode 100644 index 00000000..7f1be476 --- /dev/null +++ b/packages/laravel/tests/Fixtures/ShipmentUpdate.php @@ -0,0 +1,8 @@ + 202, 'body' => '{"message_id":"' . self::MESSAGE_ID . '","replayed":false}']; + private const FAILOVER = ['transport' => 'failover', 'mailers' => ['posthog', 'archive']]; + + private ?LocalHttpServer $api = null; + + protected function getPackageProviders($app): array + { + return [PostHogServiceProvider::class]; + } + + protected function defineEnvironment($app): void + { + $app['config']->set('posthog.api_key', 'phc_project'); + $app['config']->set('posthog.secret_key', 'phs_secret'); + $app['config']->set('posthog.sdk.consumer', 'noop'); + $app['config']->set('mail.default', 'posthog'); + $app['config']->set('mail.mailers.posthog', ['transport' => 'posthog']); + $app['config']->set('mail.mailers.archive', ['transport' => 'array']); + } + + protected function tearDown(): void + { + $this->api?->stop(); + parent::tearDown(); + } + + private function sendApi(array $responses = [self::SENT]): LocalHttpServer + { + // The core SDK's loopback HTTP server, which records each request it answers. + require_once __DIR__ . '/../../../test/LocalHttpServer.php'; + $this->api = new LocalHttpServer($responses); + $this->app['config']->set('posthog.sdk.app_host', 'http://' . $this->api->address()); + + return $this->api; + } + + /** + * @return array{requestLine: string, headers: array, body: string} + */ + private function onlySend(): array + { + $requests = $this->api->requests(); + $this->assertCount(1, $requests); + $this->assertSame('POST /api/projects/@current/messaging/send/email/ HTTP/1.1', $requests[0]['requestLine']); + + return $requests[0]; + } + + private function templateKeyOfOnlySend(): string + { + return json_decode($this->onlySend()['body'], true)['template_key']; + } + + public function testAMailableSendsThroughThePostHogMailerUnderItsClassName(): void + { + $this->sendApi(); + + $sent = Mail::to('ana@example.com')->send(new OrderShipped()); + + $request = $this->onlySend(); + $this->assertSame('Bearer phs_secret', $request['headers']['authorization']); + $this->assertSame('laravel/' . PostHog::VERSION, $request['headers']['x-posthog-integration']); + $body = json_decode($request['body'], true); + $this->assertSame('order-shipped', $body['template_key']); + $this->assertSame('ana@example.com', $body['to']); + $this->assertSame('shop@example.com', $body['from']); + $this->assertSame('Your order shipped', $body['subject']); + $this->assertSame('

On its way.

', $body['html']); + $this->assertSame(self::MESSAGE_ID, $sent->getMessageId()); + } + + public function testAMailNotificationSendsUnderTheNotificationClassName(): void + { + $this->sendApi(); + + Notification::send( + (new AnonymousNotifiable())->route('mail', 'ana@example.com'), + new InvoicePaid() + ); + + $body = json_decode($this->onlySend()['body'], true); + $this->assertSame('invoice-paid', $body['template_key']); + $this->assertSame('Invoice paid', $body['subject']); + $this->assertSame('ana@example.com', $body['to']); + } + + public function testAMailableSendsUnderItsClassNameThroughAFailoverMailer(): void + { + $this->app['config']->set('mail.mailers.failover', self::FAILOVER); + $this->sendApi(); + + Mail::mailer('failover')->to('ana@example.com')->send(new OrderShipped()); + + $this->assertSame('order-shipped', $this->templateKeyOfOnlySend()); + } + + public function testTwoMailablesThatReadAlikeSendUnderTheirOwnClassNamesThroughAFailoverMailer(): void + { + $this->app['config']->set('mail.mailers.failover', self::FAILOVER); + $this->sendApi([self::SENT, self::SENT]); + + // The app keeps the first sent mail, as a log or an event listener might. + $first = Mail::mailer('failover')->to('ana@example.com')->send(new OrderShipped()); + Mail::mailer('failover')->to('ana@example.com')->send(new ShipmentUpdate()); + + $keys = array_map( + fn(array $request) => json_decode($request['body'], true)['template_key'], + $this->api->requests() + ); + $this->assertSame(['order-shipped', 'shipment-update'], $keys); + $this->assertNotNull($first); + } + + public function testMailWithNoClassThatReadsLikeAnEarlierMailableSendsUnderTheDefaultTemplateKey(): void + { + $this->app['config']->set('mail.mailers.posthog.default_template_key', 'receipts'); + $this->app['config']->set('mail.mailers.failover', self::FAILOVER); + $this->sendApi([self::SENT, self::SENT]); + + $first = Mail::mailer('failover')->to('ana@example.com')->send(new OrderShipped()); + Mail::mailer('failover')->html('

On its way.

', function ($message) { + $message->from('shop@example.com')->to('ana@example.com')->subject('Your order shipped'); + }); + + $keys = array_map( + fn(array $request) => json_decode($request['body'], true)['template_key'], + $this->api->requests() + ); + $this->assertSame(['order-shipped', 'receipts'], $keys); + $this->assertNotNull($first); + } + + public function testAMailSentWhileAnotherIsSendingLeavesTheOtherItsClassName(): void + { + $this->app['config']->set('mail.mailers.failover', self::FAILOVER); + $this->sendApi(); + $archived = null; + Event::listen(MessageSending::class, function (MessageSending $event) use (&$archived) { + if ($archived === null && ($event->data['__laravel_mailable'] ?? null) === OrderShipped::class) { + $archived = Mail::mailer('archive')->to('ana@example.com')->send(new ShipmentUpdate()); + } + }); + + Mail::mailer('failover')->to('ana@example.com')->send(new OrderShipped()); + + $this->assertNotNull($archived); + $this->assertSame('order-shipped', $this->templateKeyOfOnlySend()); + } + + /** + * @return array + */ + public static function templateKeysTheSendApiRejects(): array + { + return ['a space' => ['App mail'], 'empty' => [''], 'too long' => [str_repeat('a', 257)]]; + } + + #[DataProvider('templateKeysTheSendApiRejects')] + public function testAMailerWithADefaultTemplateKeyTheSendApiRejectsIsRefusedForEveryMail(string $key): void + { + $this->app['config']->set('mail.mailers.posthog.default_template_key', $key); + $this->sendApi(); + + try { + Mail::to('ana@example.com')->send(new OrderShipped()); + $this->fail('A mailer with an invalid default template key sent.'); + } catch (InvalidArgumentException $refusal) { + $this->assertStringContainsString('default template key', $refusal->getMessage()); + } + $this->assertSame([], $this->api->requests()); + } + + public function testAMailableSendsUnderItsClassNameThroughAMailerBuiltOnDemand(): void + { + $this->sendApi(); + + Mail::build(['transport' => 'posthog'])->to('ana@example.com')->send(new OrderShipped()); + + $this->assertSame('order-shipped', $this->templateKeyOfOnlySend()); + } + + public function testAMailableFailingOverFromPostHogReachesTheNextMailerWithoutPostHogHeaders(): void + { + $this->app['config']->set('mail.mailers.failover', self::FAILOVER); + $this->sendApi([[ + 'status' => 400, + 'body' => '{"type":"validation_error","code":"invalid_input","detail":"Bad."}', + ]]); + + $sent = []; + Event::listen(MessageSent::class, function (MessageSent $event) use (&$sent) { + $sent[] = $event->message; + }); + + Mail::mailer('failover')->to('ana@example.com')->send(new OrderShipped([ + 'X-PostHog-Distinct-Id' => 'user_123', + 'X-PostHog-Idempotency-Key' => 'order-42:order-shipped', + ])); + + $this->assertCount(1, $this->api->requests()); + $this->assertCount(1, $sent); + $headers = $sent[0]->getHeaders()->getNames(); + $this->assertSame([], array_values(preg_grep('/^x-posthog-/i', $headers))); + } + + public function testAnotherMailerSendsTheMailableWithoutPostHogHeaders(): void + { + Mail::mailer('archive')->to('ana@example.com')->send(new OrderShipped()); + + $messages = Mail::mailer('archive')->getSymfonyTransport()->messages(); + $this->assertCount(1, $messages); + $this->assertFalse($messages[0]->getOriginalMessage()->getHeaders()->has('X-PostHog-Template-Key')); + } + + public function testAClassNameLongerThanTheTemplateKeyLimitIsCutToFit(): void + { + // A class name this long would outgrow a file name, so the test declares it. + $name = 'OrderShipped' . str_repeat('AndEverythingElse', 20); + eval("namespace PostHog\\Laravel\\Tests\\Fixtures; class $name extends OrderShipped {}"); + $mailable = 'PostHog\\Laravel\\Tests\\Fixtures\\' . $name; + $this->sendApi(); + + Mail::to('ana@example.com')->send(new $mailable()); + + $key = $this->templateKeyOfOnlySend(); + $this->assertSame(256, strlen($key)); + $this->assertStringStartsWith('order-shipped-and-everything-else-and-everything-else', $key); + } + + public function testTheMailableSetsItsOwnTemplateKeyAndOptionsInHeaders(): void + { + $this->sendApi(); + + Mail::to('ana@example.com')->send(new OrderShipped([ + 'X-PostHog-Template-Key' => 'shipping-v2', + 'X-PostHog-Distinct-Id' => 'user_123', + 'X-PostHog-Idempotency-Key' => 'order-42:order-shipped', + ])); + + $request = $this->onlySend(); + $body = json_decode($request['body'], true); + $this->assertSame('shipping-v2', $body['template_key']); + $this->assertSame('user_123', $body['distinct_id']); + $this->assertSame('order-42:order-shipped', $request['headers']['idempotency-key']); + } + + public function testMailWithNoClassSendsUnderTheMailersDefaultTemplateKey(): void + { + $this->app['config']->set('mail.mailers.posthog.default_template_key', 'receipts'); + $this->sendApi(); + + Mail::raw('Thanks for your order.', function ($message) { + $message->from('shop@example.com')->to('ana@example.com')->subject('Receipt'); + }); + + $this->assertSame('receipts', $this->templateKeyOfOnlySend()); + } + + public function testMailWithNoClassAndNoDefaultSendsUnderTheIntegrationName(): void + { + $this->sendApi(); + + Mail::raw('Thanks for your order.', function ($message) { + $message->from('shop@example.com')->to('ana@example.com')->subject('Receipt'); + }); + + $this->assertSame('laravel', $this->templateKeyOfOnlySend()); + } + + public function testEachQueuedJobSendsWithItsOwnPostHogConfiguration(): void + { + $this->sendApi([self::SENT, self::SENT]); + Mail::to('ana@example.com')->send(new OrderShipped()); + + // A queue worker starts each job with fresh scoped services, such as a tenant's own secret key. + $this->app['config']->set('posthog.secret_key', 'phs_tenant'); + $this->app->forgetScopedInstances(); + Mail::to('ben@example.com')->send(new OrderShipped()); + + $requests = $this->api->requests(); + $this->assertCount(2, $requests); + $this->assertSame('Bearer phs_secret', $requests[0]['headers']['authorization']); + $this->assertSame('Bearer phs_tenant', $requests[1]['headers']['authorization']); + } + + public function testAMailablePostHogCannotCarryIsRefusedWithoutASend(): void + { + $this->sendApi(); + + try { + Mail::to(['ana@example.com', 'ben@example.com'])->send(new OrderShipped()); + $this->fail('A mail to two recipients was sent.'); + } catch (LogicException $refusal) { + $this->assertStringStartsWith('PostHog cannot send this email: multiple_to', $refusal->getMessage()); + } + $this->assertSame([], $this->api->requests()); + } + + public function testAFailedSendThrowsTheTransportErrorWithItsRetryAdvice(): void + { + $this->sendApi([[ + 'status' => 400, + 'body' => '{"type":"validation_error","code":"invalid_input","detail":"Bad from.","attr":"from"}', + ]]); + + try { + Mail::to('ana@example.com')->send(new OrderShipped()); + $this->fail('A rejected send did not throw.'); + } catch (PostHogTransportException $error) { + $this->assertSame(400, $error->getStatusCode()); + $this->assertSame('from', $error->getField()); + $this->assertFalse($error->isRetryable()); + } + } + + public function testATemplateMadeInPostHogIsRefused(): void + { + if (!class_exists(RemoteTemplateEmail::class)) { + $this->markTestSkipped('Symfony Mailer before 8.2 has no RemoteTemplateEmail to send a template.'); + } + $this->sendApi(); + $email = (new RemoteTemplateEmail()) + ->from('shop@example.com') + ->to('ana@example.com') + ->template('0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b'); + + try { + Mail::mailer('posthog')->getSymfonyTransport()->send($email); + $this->fail('A template was sent.'); + } catch (LogicException $refusal) { + $this->assertStringStartsWith( + 'PostHog cannot send this email: template_unsupported', + $refusal->getMessage() + ); + } + $this->assertSame([], $this->api->requests()); + } + + public function testAnAppThatSendsNoMailBuildsNoMailer(): void + { + $fake = PostHogFacade::fake(); + + PostHogFacade::capture('order completed', [], 'user_123'); + + $fake->assertCaptured('order completed'); + $this->assertFalse($this->app->resolved('mail.manager')); + } +}