Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

STMP module improvements #222

Merged
merged 2 commits into from
Jul 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions app/modules/Smtp/Application/Storage/EmailBodyStorage.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,13 @@ public function getMessage(string $uuid): Message
return $this->cache->get($this->getCacheKey($uuid), new Message($uuid));
}

public function cleanup(string $uuid): Message
{
$this->cache->delete($this->getCacheKey($uuid));

return new Message($uuid);
}

public function persist(Message $message): void
{
$this->cache->set(
Expand Down
19 changes: 17 additions & 2 deletions app/modules/Smtp/Interfaces/TCP/ResponseMessage.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

namespace Modules\Smtp\Interfaces\TCP;

use App\Application\Domain\ValueObjects\Uuid;

final readonly class ResponseMessage implements \Stringable
{
private const READY = 220;
Expand All @@ -23,6 +25,16 @@ public static function ok(string $message = '', string $separator = ' '): self
return new self(self::OK, $message, $separator);
}

public static function accepted(Uuid $uuid): self
{
return new self(
code: self::OK,
message: \sprintf("Ok %s", $uuid),
lineEnding: "\r",
eosSeparator: '',
);
}

public static function authRequired(string $message = 'AUTH LOGIN PLAIN'): self
{
return new self(self::OK, $message);
Expand Down Expand Up @@ -57,15 +69,18 @@ public function __construct(
public int $code,
public string $message = '',
public string $separator = " ",
public string $lineEnding = "\r\n",
public string $eosSeparator = " ",
) {}

public function __toString(): string
{
return \sprintf(
"%d%s%s\r\n",
"%d%s%s%s",
$this->code,
$this->separator,
$this->message === '' || $this->message === '0' ? '' : $this->message . ' ',
$this->message === '' || $this->message === '0' ? '' : $this->message . $this->eosSeparator,
$this->lineEnding,
);
}
}
36 changes: 23 additions & 13 deletions app/modules/Smtp/Interfaces/TCP/Service.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public function __construct(
public function handle(Request $request): ResponseInterface
{
if ($request->event === TcpEvent::Connected) {
return $this->send(ResponseMessage::ready());
return $this->makeResponse(ResponseMessage::ready());
}

$message = $this->emailBodyStorage->getMessage($request->connectionUuid);
Expand All @@ -48,30 +48,39 @@ public function handle(Request $request): ResponseInterface
);
} elseif (\preg_match('/^MAIL FROM:\s*<(.*)>/', $request->body, $matches)) {
$message->setFrom($matches[1]);
$response = $this->send(ResponseMessage::ok());
$response = $this->makeResponse(ResponseMessage::ok());
} elseif (\str_starts_with($request->body, 'AUTH')) {
$response = $this->send(ResponseMessage::enterUsername());
$response = $this->makeResponse(ResponseMessage::enterUsername());
$message->waitUsername = true;
} elseif ($message->waitUsername) {
$message->setUsername($request->body);
$response = $this->send(ResponseMessage::enterPassword());
$response = $this->makeResponse(ResponseMessage::enterPassword());
} elseif ($message->waitPassword) {
$message->setPassword($request->body);
$response = $this->send(ResponseMessage::authenticated());
$response = $this->makeResponse(ResponseMessage::authenticated());
} elseif (\preg_match('/^RCPT TO:\s*<(.*)>/', $request->body, $matches)) {
$message->addRecipient($matches[1]);
$response = $this->send(ResponseMessage::ok());
$response = $this->makeResponse(ResponseMessage::ok());
} elseif (\str_starts_with($request->body, 'QUIT')) {
$response = $this->send(ResponseMessage::closing(), close: true);
$response = $this->makeResponse(ResponseMessage::closing(), close: true);
$message = $this->emailBodyStorage->cleanup($request->connectionUuid);
} elseif ($request->body === "DATA\r\n") {
$response = $this->send(ResponseMessage::provideBody());
$response = $this->makeResponse(ResponseMessage::provideBody());
$message->waitBody = true;
} elseif ($request->body === "RSET\r\n") {
$message = $this->emailBodyStorage->cleanup($request->connectionUuid);
$response = $this->makeResponse(ResponseMessage::ok());
} elseif ($request->body === "NOOP\r\n") {
$response = $this->makeResponse(ResponseMessage::ok());
} elseif ($message->waitBody) {
$response = $this->send(ResponseMessage::ok());
$message->appendBody($request->body);

$response = $this->makeResponse(ResponseMessage::ok());

if ($message->bodyHasEos()) {
$this->dispatchMessage($message->parse(), project: $message->username);
$uuid = $this->dispatchMessage($message->parse(), project: $message->username);

$response = $this->makeResponse(ResponseMessage::accepted($uuid));
$dispatched = true;
}
}
Expand All @@ -89,12 +98,11 @@ public function handle(Request $request): ResponseInterface
return $response;
}

private function dispatchMessage(Message $message, ?string $project = null): void
private function dispatchMessage(Message $message, ?string $project = null): Uuid
{
$uuid = Uuid::generate();
$data = $message->jsonSerialize();


$result = $this->attachments->store(eventUuid: $uuid, attachments: $message->attachments);
// TODO: Refactor this
foreach ($result as $cid => $url) {
Expand All @@ -109,9 +117,11 @@ private function dispatchMessage(Message $message, ?string $project = null): voi
uuid: $uuid,
),
);

return $uuid;
}

private function send(ResponseMessage $message, bool $close = false): RespondMessage
private function makeResponse(ResponseMessage $message, bool $close = false): RespondMessage
{
return new RespondMessage((string) $message, $close);
}
Expand Down
31 changes: 25 additions & 6 deletions tests/Feature/Interfaces/TCP/Smtp/EmailTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Ramsey\Uuid\Uuid;
use Spiral\RoadRunner\Tcp\TcpEvent;
use Spiral\RoadRunnerBridge\Tcp\Response\CloseConnection;
use Symfony\Component\Mailer\SentMessage;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Part\DataPart;
Expand Down Expand Up @@ -75,7 +76,22 @@ public function testSendEmail(): void
}),
);

// Assert hello.txt is persisted to a database
// Assert sample.pdf is persisted to a database
$this->attachments->shouldReceive('store')
->once()
->with(
\Mockery::on(function (Attachment $attachment) {
$this->assertSame('sample.pdf', $attachment->getFilename());
$this->assertSame(61752, $attachment->getSize());
$this->assertSame('application/pdf', $attachment->getMime());

// Check attachments storage
$this->bucket->assertCreated($attachment->getPath());
return true;
}),
);

// Assert logo.svg is persisted to a database
$this->attachments->shouldReceive('store')
->once()
->with(
Expand All @@ -90,15 +106,17 @@ public function testSendEmail(): void
}),
);

$client->send($email);
$sentMessage = $client->send($email);

$this->validateMessage($id, (string) $connectionUuid);

$response = $this->handleSmtpRequest(message: '', event: TCPEvent::Close);
$this->assertInstanceOf(CloseConnection::class, $response);

$this->assertEventPushed('default');
$this->assertEventPushed($sentMessage, 'default');
}


private function getEmailMessage(string $uuid): Message
{
return $this->get(EmailBodyStorage::class)->getMessage($uuid);
Expand Down Expand Up @@ -181,9 +199,9 @@ private function validateMessage(string $messageId, string $uuid): void
);
}

private function assertEventPushed(?string $project = null): void
private function assertEventPushed(SentMessage $message, ?string $project = null): void
{
$this->broadcastig->assertPushed(new EventsChannel($project), function (array $data) use ($project) {
$this->broadcastig->assertPushed(new EventsChannel($project), function (array $data) use ($message, $project) {
$this->assertSame('event.received', $data['event']);
$this->assertSame('smtp', $data['data']['type']);
$this->assertSame($project, $data['data']['project']);
Expand Down Expand Up @@ -212,7 +230,7 @@ private function assertEventPushed(?string $project = null): void
],
], $data['data']['payload']);

$this->assertNotEmpty($data['data']['uuid']);
$this->assertSame($message->getMessageId(), $data['data']['uuid']);
$this->assertNotEmpty($data['data']['timestamp']);

return true;
Expand All @@ -235,6 +253,7 @@ public function buildEmail(): Email
)
->addFrom(new Address('[email protected]', 'Bob Example'),)
->attachFromPath(path: __DIR__ . '/hello.txt',)
->attachFromPath(path: __DIR__ . '/sample.pdf',)
->attachFromPath(path: __DIR__ . '/logo.svg')
->addPart(
(new DataPart(new File(__DIR__ . '/logo.svg'), 'logo-embeddable'))->asInline()->setContentId(
Expand Down
Binary file added tests/Feature/Interfaces/TCP/Smtp/sample.pdf
Binary file not shown.
Loading